View PDF In Android - Example


In this Example we will see how to view a pdf file through an android app. Here we will open the pdf file saved in the SD card with an application to view the pdf file like the Adobe Reader , Quick Office or any other application capable of reading pdf files.

In this application on tapping a button we check for the existence of the pdf file in the SD card. If the file exists we call the reader application via Intents. In the due course if the reader application is not found it is notified by catching the exception ActivityNotFoundException.


So lets start:

1.Create an Android Application Project with any Project Name and Package Name. Create an Activity and Layout file for the same like MainActivity & activity_main.

2.Design the screen for the activity with a button as below

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Vibrator" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="124dp"
        android:text="Welcome to AndroidBite !!!"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <Button
        android:id="@+id/bPressMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Press Me !!!" />

</RelativeLayout>

3.Now in the activity, we create a File instance and construct it using specified directory and name. Then we set the Uri from the file instance and start the intent Intent.ACTION_VIEW . This intents data is set with the uri and the MIME Type for pdf is set as application/pdf before calling the intent.

MainActivity.java:
import java.io.File;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Button button = (Button) findViewById(R.id.bPressMe);

  button.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {

    File pdfFile = new File(Environment
      .getExternalStorageDirectory(), "Case Study.pdf");

    try {
     if (pdfFile.exists()) {
      Uri path = Uri.fromFile(pdfFile);
      Intent objIntent = new Intent(Intent.ACTION_VIEW);
      objIntent.setDataAndType(path, "application/pdf");
      objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(objIntent);
     } else {
      Toast.makeText(MainActivity.this, "File NotFound",
        Toast.LENGTH_SHORT).show();
     }
    } catch (ActivityNotFoundException e) {
     Toast.makeText(MainActivity.this,
       "No Viewer Application Found", Toast.LENGTH_SHORT)
       .show();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });

 }

}
4.Include the WRITE_EXTERNAL_STORAGE permission in the manifest file(permission for both reading and writing).
5.Run the application by right clicking the project Run As->Android Application. If everything goes well the output will be similar to the one below

Output:

Android Voice Recognition Example


Google provides an option to search the web using voice command . Let us create a similar Voice Recognition Application( Speech to text Application) in android. In this example we will have a button to initiate speech recognition, by tapping on it we call the voice/speech recognition API where the voice is recognized and converted into text .Finally we will display the results that was recognized in a ListView.

Voice recognition featured in android is achieved using the RecognizerIntent.Use the Recognizer class in an intent to call the voice API.Here we check for the recognizer in the device if available the speech to text happen else we show a toast displaying 'Recognizer Not Found'

Note: This application will not work in emulator since it does not have the recognizer, so test it in a device and it also requires an internet connection.

So Lets Start:

1.Create an android application with any package name and project name.Name the Activity as VoiceActivity and the layout file as voice_demo.
2.Let us design the UI for the activity with a TextView,Button and ListView as follows

voice_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="Click the button below and start speaking"
        android:textSize="18dp" />

    <Button
        android:id="@+id/speakButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/voic_img" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

</LinearLayout>


3.In the Activity file we call the RecognizerIntent.ACTION_RECOGNIZE_SPEECH. Starts an activity that will prompt the user for speech and send it through a speech recognizer. The results will be returned via activity result.

VoiceActivity:

package com.example.voice;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class VoiceActivity extends Activity {

 private static final int REQUEST_CODE = 1234;
 private ListView resultList;
 Button speakButton;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.voice_demo);

  speakButton = (Button) findViewById(R.id.speakButton);

  resultList = (ListView) findViewById(R.id.list);

  // Disable button if no recognition service is present
  PackageManager pm = getPackageManager();
  List<resolveinfo> activities = pm.queryIntentActivities(new Intent(
    RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
  if (activities.size() == 0) {
   speakButton.setEnabled(false);
   Toast.makeText(getApplicationContext(), "Recognizer Not Found",
     1000).show();
  }
  speakButton.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    startVoiceRecognitionActivity();
   }
  });
 }

 private void startVoiceRecognitionActivity() {
  Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
  intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
  intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
    "AndroidBite Voice Recognition...");
  startActivityForResult(intent, REQUEST_CODE);
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == REQUEST_CODE &amp;&amp; resultCode == RESULT_OK) {
   ArrayList<string> matches = data
     .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
   resultList.setAdapter(new ArrayAdapter<string>(this,
     android.R.layout.simple_list_item_1, matches));
  }
  super.onActivityResult(requestCode, resultCode, data);
 }
}




4.Alter the manifest file by enabling internet permission
<uses-permission android:name="android.permission.INTERNET" />
5.Run the application by right clicking the project Run As->Android Application.You would see and output similar to the one below

Output:



Android Radio Button / Radio Group Example


In this example we will see how to add radio buttons to our android application. We can render a radio button using android.widget.RadioButton class ,but having a single radio button is of no use. Android provides android.widget.RadioGroup to group the radio buttons so that if one radio button is selected within a group others are deselected. Here we will design a screen having radio button within a group and toast the selected item.

Lets start:

1. Create an android application with any packagename and project name. Name the activity as AndroidRadioActivity.java and the layout file as main.xml
2.Let us design the layout file with a TextView posting a question followed by radio buttons and a display button.

main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="How do you rate Android?" />

    <RadioGroup
        android:id="@+id/radioOptions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="1" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2" />

        <RadioButton
            android:id="@+id/radio3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="3" />

        <RadioButton
            android:id="@+id/radio4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="4" />

        <RadioButton
            android:id="@+id/radio5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="5" />
    </RadioGroup>

    <Button
        android:id="@+id/btnDisplayRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Rating" />

</LinearLayout>
3.Now in the activity file let us display the text associated with the radio button selected on tapping a display rating button.

AndroidRadioActivity:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class AndroidRadioActivity extends Activity {

 private RadioGroup radioOptions;
 private RadioButton radioButton;
 private Button btnDisplay;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  radioOptions = (RadioGroup) findViewById(R.id.radioOptions);
  btnDisplay = (Button) findViewById(R.id.btnDisplayRating);

  btnDisplay.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    int selectedId = radioOptions.getCheckedRadioButtonId();

    radioButton = (RadioButton) findViewById(selectedId);
    Toast.makeText(AndroidRadioActivity.this,
      "You Rated as " + radioButton.getText(),
      Toast.LENGTH_SHORT).show();

   }

  });
 }

}


4.Build the application and run the project. The output would be similar to the one below.

Output:

Android Vibrator Example



In this example we will learn how to make your phone to vibrate. Vibrate option is handy to providing users haptic feedback like when the phone rings,when you receive a notification may it be a message or anything. Here we will provide an example, where the phone vibrates for the given amount of time on a button press.

Android provides an abstract class Vibrator which is helpful in vibrating the device by obtaining an instance of the system vibrator with getSystemService(String) with constant VIBTRATOR_SERVICE as argument.

So lets start:

1.Create an android application project with any package and project name. Name the activity as VibratorExample and the layout file as activity_vibrator.
2.So let us design the UI for the activity with a TextView and a Button

activity_vibrator.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Vibrator" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="124dp"
android:text="Welcome to AndroidBite !!!"
android:textColor="@android:color/black"
android:textSize="20sp" />

<Button
android:id="@+id/bPressMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Press Me !!!" />

</RelativeLayout>

3.Now in the activity file create an instance for the vibrator class and call the method vibrate with the instance for the specified duration say 1000 milliseconds.

VibratorExample.java:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class VibratorExample extends Activity {

 Button bPressMe;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_vibrator);
  bPressMe = (Button) findViewById(R.id.bPressMe);
  bPressMe.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {

    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(1000);
   }
  });
 }

}


4. Add required permissions in the manifest file for vibration to occur

<uses-permission android:name="android.permission.VIBRATE" />

5.Now run the application by right clicking the project Run As->Android Application. The output will be similar to the one below. The phone vibrates for 1 sec when the button is pressed.

Output: