Showing posts with label Android Beginner. Show all posts
Showing posts with label Android Beginner. Show all posts

Saturday 24 August 2013

Android TabActivity Example

// siddhu vydyabhushana // 6 comments
As we know Tab-Activity is now depreciated  in Android, but some time we use it for create simple Tab pages in our application. So today I am going to share tutorial for Tab Host Activity in android. It is a simple tab activity demo, group child activity and pager tab example I will share soon. Hope my blog help you. Please follow step by step my blog for create simple Tab Layout-


Print Screen: 


android tabactivity example
1)Create a new project, name TabHostDemo.
2)Create an  TabHostActivity and extend it to TabActivity.
3)Create 3 other activity name-Homeactivity, AboutActivity, ContactActivity.
4)Create layout activity_tab_host.xml .
5)Create another 3 layout for Home, About, Contact Activity, name activity_home, activity_about, activity_contact.
6)Do optional activity for change tab images on selection.Create ic_tab_home, ic_tab_about, ic_tab_contact.
Note-this step is not must, you can direct put your images in your TabHostActivity-
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, HomeActivity.class);
spec = tabHost.newTabSpec("home")
.setIndicator("HOME", res.getDrawable(R.drawable.home))//set here
.setContent(intent);
tabHost.addTab(spec);
7)Add images - home.png, about.png, contact.png in drawable download below images-
android tabactivity

android tabactivity

android tabactivity

android tabactivity

android tabactivity

android tabactivity

8)Add activity in manifest.xml
9)Run your project and enjoy :)

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;

public class TabHostActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_host);

Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab

// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, HomeActivity.class);
spec = tabHost.newTabSpec("home")
.setIndicator("HOME", res.getDrawable(R.drawable.ic_tab_home))
.setContent(intent);
tabHost.addTab(spec);

// Do the same for the other tabs

intent = new Intent().setClass(this, AboutActivity.class);
spec = tabHost.newTabSpec("about")
.setIndicator("ABOUT", res.getDrawable(R.drawable.ic_tab_about))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, ContactActivity.class);
spec = tabHost
.newTabSpec("contact")
.setIndicator("CONTACT",
res.getDrawable(R.drawable.ic_tab_contact))
.setContent(intent);
tabHost.addTab(spec);
//set tab which one you want open first time 0 or 1 or 2
tabHost.setCurrentTab(0);
}
}

HomeActivity.java

import android.app.Activity;
import android.os.Bundle;

public class HomeActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
AboutActivity.java
import android.app.Activity;
import android.os.Bundle;

public class AboutActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
}
ContactActivity.java
import android.app.Activity;
import android.os.Bundle;

public class ContactActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
}
}
activity_tab_host.xml

   
     

        

        
     
    


Activity_Home.xml


    


activity_about.xml


    
Android Manifest file


    

    
        
            
                

                
            
        
        
             
                  
    


For further files download the zippedfile and enjoyy!!!!!!!! keep smiling and commenting
13) DOWNLOAD ZIP CODE
Please feel free to post your testimonials regarding my work here. Please leave your review by clicking on comment below this post.

Thanks.
Read More

Scroll view Example in android

// siddhu vydyabhushana // 2 comments

Simple Scroll-View example in Android | Vertical Scroll View Demo in Android | Scroll View in Android

Hello Friends, On a specific demand I am going to share very simple code for vertical scroll view in android. Hope it will help you-
scroll view in android

1)MainActivity.java


package com.example.scrollviewdemo;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}

2)activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/imageView1" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <Button
                android:id="@+id/button1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button3"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button4"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button7"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button8"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button9"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button10"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button11"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button12"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button13"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />

            <Button
                android:id="@+id/button14"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Button" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

Thanks,
Read More

Android Fill_parent and Wrap_Content Example

// siddhu vydyabhushana // 1 comment
In Android, you always put either “wrap_content” or “fill_parent” on component’s attribute “layout_width” and “layout_height“, did you wonder what’s the different?
See following definition :
  1. wrap_content – The component just want to display big enough to enclose its content only.
  2. fill_parent – The component want to display as big as its parent, and fill in the remaining spaces. (renamed match_parent in API Level 8)
Above terms may not make sense now, let see following demonstration :

1. wrap_content

A button component, set “wrap_content” on both width and height attribute. It tell Android to display the button big enough to enclose it’s content “Button ABC” only.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <Button
        android:id="@+id/btnButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button ABC"/>
 
</RelativeLayout>
                                         android wrap-content example1

2. fill_parent – width

Change the “layout_width” to “fill_parent“, now, the button’s width will fill in the remaining spaces, just as big as it’s parent “RelativeLayout“, but button’s height is still big enough to enclose it’s content only.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <Button
        android:id="@+id/btnButton1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Button ABC"/>
 
</RelativeLayout>
                                       android wrap-content example2

3. fill_parent – height

Change the “layout_height” to “fill_parent“, now, the button’s height will fill in the remaining spaces, just as big as it’s parent “RelativeLayout“, but button’s width is still big enough to enclose it’s content only.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <Button
        android:id="@+id/btnButton1"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="Button ABC"/>
 
</RelativeLayout>
                                         android wrap-content example3

4. fill_parent – width, height

Change the both “layout_width” and “layout_height” to “fill_parent“, the button will display as big as the whole device screen, it just fill in the entire screen space.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <Button
        android:id="@+id/btnButton1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="Button ABC"/>
 
</RelativeLayout>
                                           android wrap-content example4
Note
Actually, you can specifying an exact width and height, but it’s not recommended, due to Android variety of devices screen size. You just do not know what size of Android device is running your fantasy application.
Read More

Android Beginner: Android activity tutorial

// siddhu vydyabhushana // Leave a Comment
In Android, an activity is represent a single screen. Most applications have multiple activities to represent different screens, for example, one activity to display a list of the application settings, another activity to display the application status.
Note
Refer to this official Android activity article to understand more about Android activity.
In this tutorial, we show you how to interact with activity, when a button is clicked, navigate from current screen (current activity) to another screen (another activity).
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. XML Layouts

Create following two XML layout files in “res/layout/” folder :
  1. res/layout/main.xml – Represent screen 1
  2. res/layout/main2.xml – Represent screen 2
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    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="I&apos;m screen 1 (main.xml)"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click me to another screen" />
 
</LinearLayout>
File : res/layout/main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I&apos;m screen 2 (main2.xml)"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</LinearLayout>

2. Activities

Create two activity classes :
  1. AppActivity.java –> main.xml
  2. App2Activity.java –> main2.xml
To navigate from one screen to another screen, use following code :
    Intent intent = new Intent(context, anotherActivity.class);
    startActivity(intent);
File : AppActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
 
public class AppActivity extends Activity {
 
	Button button;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		addListenerOnButton();
	}
 
	public void addListenerOnButton() {
 
		final Context context = this;
 
		button = (Button) findViewById(R.id.button1);
 
		button.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View arg0) {
 
			    Intent intent = new Intent(context, App2Activity.class);
                            startActivity(intent);   
 
			}
 
		});
 
	}
 
}
File : App2Activity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
 
public class App2Activity extends Activity {
 
	Button button;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main2);
	}
 
}

3. AndroidManifest.xml

Declares above two activity classes in AndroidManifest.xml.
File : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mkyong.android"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="10" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AppActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:label="@string/app_name"
            android:name=".App2Activity" >
        </activity>
    </application>
 
</manifest>

4. Demo

Run application.
AppActivity.java (main.xml) screen is display.
                                       android activity demo1
When above button is clicked, it will navigate to another screen App2Activity.java (main2.xml).
android activity demo2
Add caption
                                  

Download Source Code

 
Read More

Monday 19 August 2013

How to take screenshots of emulator in eclipse

// siddhu vydyabhushana // Leave a Comment
If you are an Android developer then you are already taking lot of screen shots of your app. For documentation purpose or for putting it in Google Play market. Taking screen shots of Android in phone is easy in today’s smart phones like Samsung Galaxy series. But most of the time we would need to grab the screen from Android emulator.
Here’s a simple but very useful trick to capture screen shot of Android application via Eclipse. For this you must have installed Android’s ADT plugin in Eclipse.
Follow these simple steps to capture the current screen of your current Emulator.
In eclipse, Open Windows > Show View > Others… (Shortcut Alt + Shift + Q, Q)
                   android-eclipse-devices-view
From the Show View dialog, open Android and select Devices.
                                   android-eclipse-devices-view-select
This will open a new Devices view in your eclipse. Select the Emulator that is running currently and that you want to capture screen of and click Camera icon on right side.
                      android-eclipse-capture-screen-shot
This will open Device Screen Capture dialog. Press Refresh button to capture current screen and press Save to save it in PNG format on disk.
                      android-eclipse-screen-capture
Happy screen grabing :)
Read More

Android Application for load image from galary

// siddhu vydyabhushana // 1 comment
Since few days I am working on an Android app and learning all the nitty gritty of its APIs. I will share few How-to stuffs that we frequently require in Android.
To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.
Let us create an example with following requirement:
  1. First screen shows user with and Image view and a button to loan Picture.
  2. On click of “Load Picture” button, user will be redirected to Android’s Image Gallery where she can select one image.
  3. Once the image is selected, the image will be loaded in Image view on main screen.
So lets start.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as ImageGalleryDemo and select Android Runtime 2.1 or sdk 7.
Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.
Open layout/main.xml in your android project and replace its content with following:
File: res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"></ImageView>
    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Load Picture"
        android:layout_gravity="center"></Button>
</LinearLayout>
So our Android’s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is imgView and that of Button is buttonLoadPicture.

Step 3: Android Java Code to trigger Image Gallery Intent

We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.
Thus, on click of button we will trigger following code:
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 
startActivityForResult(i, RESULT_LOAD_IMAGE);
Note how we passed an integer RESULT_LOAD_IMAGE to startActivityForResult() method. This is to handle the result back when an image is selected from Image Gallery.
So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?

Step 4: Getting back selected Image details in Main Activity

Once user will select an image, the method onActivityResult() of our main activity will be called. We need to handle the data in this method as follows:
@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
      
     if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
         Uri selectedImage = data.getData();
         String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
         Cursor cursor = getContentResolver().query(selectedImage,
                 filePathColumn, null, null, null);
         cursor.moveToFirst();
 
         int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
         String picturePath = cursor.getString(columnIndex);
         cursor.close();
                      
         // String picturePath contains the path of selected Image
     }
Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to startActivityForResult() method.

Final Code

Below is the final code of ImageGalleryDemoActivity class.
package net.viralpatel.android.imagegalleray;
 
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
public class ImageGalleryDemoActivity extends Activity {
     
     
    private static int RESULT_LOAD_IMAGE = 1;
     
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View arg0) {
                 
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }
     
     
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
 
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
             
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
         
        }
     
     
    }
}

Screen shots of Android app

First screen: Lets user to trigger Image Gallery
                                              android-gallery-intent-example
User can select an image from Image Gallery
                                                 android-gallery-intent-select-image
Once user selects an image, the same will be displayed on our main activity
                                                 android-gallery-intent-example-demo

Download Source Code

ImageGalleryDemo.zip (46 KB)
Read More

Sunday 18 August 2013

Android application for text to speech

// siddhu vydyabhushana // 1 comment
This tutorial will teach you to give your applications a voice with the Android SDK text to speech engine!

The Android text to speech engine still seems to be a pretty underused resource in Android apps. However, implementing it in your own applications is straightforward. There are a few potential issues and choices you need to consider, but for most purposes, the process is not a complex one. In this tutorial we jump around a bit within one Android Activity, but don’t worry, the complete code is listed at the end. The aim is to give you a clear idea of the what’s going on at each processing stage so that you can successfully use the function in any app.

Step 1: Start or Open an Android Project

If you already have an application you want to implement Text To Speech with, open it in your IDE. Otherwise, create a new Android project. You can use the code in this tutorial with any Activity class. For demonstration, we will first create some user interface elements. Again, if you already have your own UI, you can use it instead.

Step 2: Create User Interface Elements

Add some user interface elements to your application, allowing the user to enter text and initiate speech playback using a button. In the XML layout file for your Activity, which will be “main.xml” if you created a new project, add the following markup:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<TextView android:id="@+id/intro"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Enter some text:"
/>
<EditText android:id="@+id/enter"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>
<Button android:id="@+id/speak"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Speak"
/>
Your XML layout files should be in the “res/layout” directory within your application package. This code adds three user interface elements: a label with some instructional text in it, an editable text-field, and a button. The user will be able to enter text into the field, then press the button to hear it spoken. If you are using an existing project, you can of course use the interface elements you already have. If you are using these new elements, you can alter them to suit the design of your own app.
Speech App User Interface

Step 3: Listen For User Events

Open the Java file for the Activity you want to implement TTS in. If you created a new app, open the main class file. In Eclipse, your Activity should automatically have the “onCreate” method within it and should extend “Activity” as part of its declaration. At the top of the class file, add the following import statements so that your app can listen for button clicks:
1
2
3
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
Alter the class declaration to implement the “OnClickListener” interface, as in the following sample line of code:
1
public class SpeakingAndroid extends Activity implements OnClickListener
Alter the class name to suit your own application details. Your IDE may display warnings because your class has not yet implemented “OnClickListener” correctly – just ignore these for now. In the “onCreate” method, add the following code:
1
2
Button speakButton = (Button)findViewById(R.id.speak);
speakButton.setOnClickListener(this);
If you did not add the button using “speak” as its ID in your XML layout file, alter this code to reflect the correct ID value. This sets your Activity class up to handle user button clicks. Add the following method outline to your class:
1
2
3
public void onClick(View v) {
//handle user clicks here
}
Inside this method you will begin the Text To Speech functionality.

Step 4: Get the Entered Text

When the user clicks the button, your app needs to get any text entered so that you can pass it to the TTS method. Add the following import statement at the top of your class declaration so that your code can refer to the editable text-field:
1
import android.widget.EditText;
Inside your “onClick” method, add the following code:
1
2
EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();
This code first acquires a reference to the text-field using its ID value, so alter this if you used a different value in your layout XML. Next, the code gets the text from the field and stores it as a string variable. If the user has not entered any text this will be empty. Depending on the logic within your application you may wish to add a conditional test, checking that the string is not null or zero in length, but this is not generally necessary.
Entering Text

Step 5: Create a Speech Method

To keep your Android classes well-organized, it’s advisable to create dedicated methods for processes you may want to use more than once. Add the following method outline to your Activity:
1
2
3
private void speakWords(String speech) {
//implement TTS here
}
This is where your TTS processing will go. Back in the “onClick” listener method, call this new method, passing it the string variable your code copied from the text-field:
1
speakWords(words);
Using a method for the TTS process means that your code can call on it elsewhere if necessary.

Step 6: Implement TTS Within the Class

To utilize the TTS facility, you need to make a few more changes to your class declaration. Add the following import statements for the TTS classes at the top of your file:
1
2
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
You also need to implement one more interface, so alter your class declaration outline to add “OnInitListener” as in the following example:
1
public class SpeakingAndroid extends Activity implements OnClickListener, OnInitListener
Remember to use your own class name. Again, your IDE will alert you to the fact that you haven’t yet implemented this interface but don’t worry, you will soon.

Step 7: Check for TTS Data

Your app needs to check that the user has the data necessary for the TTS function before you call its methods. Declare and instantiate the following instance variable at the top of your Activity class declaration, before the “onCreate” method:
1
private int MY_DATA_CHECK_CODE = 0;
Add the following import statement at the top of the class:
1
import android.content.Intent;
In the “onCreate” method, add the following:
1
2
3
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
This code creates a new Intent purely for the purposes of checking the user data. When the checking process is complete, the code will call the “onActivityResult” method.

Step 8: Create a TTS Instance

Declare an instance variable for your TTS object at the top of the class declaration, also before the “onCreate” method:
1
private TextToSpeech myTTS;
Add the “onActivityResult” to your class as follows:
1
2
3
4
5
6
7
8
9
10
11
12
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MY_DATA_CHECK_CODE) {
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            myTTS = new TextToSpeech(this, this);
        }
        else {
            Intent installTTSIntent = new Intent();
            installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installTTSIntent);
        }
        }
}
When the data checking Intent completes, the app calls this method, passing it the “MY_DATA_CHECK_CODE” variable indicating whether or not the user has the TTS data installed. If the data is present, the code goes ahead and creates an instance of the TTS class. If the data is not present, the app will prompt the user to install it.

Step 9: Provide the onInit Method

Your class declaration is implementing “OnInitListener” so you must provide an “onInit” method. In this method, you can carry out any final set-up checks you need, as well as choosing settings for your TTS instance, such as language and locale options. Add the following import statement at the top of your class:
1
import java.util.Locale;
Add the “onInit” method to the class as follows:
1
2
3
4
5
public void onInit(int initStatus) {
    if (initStatus == TextToSpeech.SUCCESS) {
        myTTS.setLanguage(Locale.US);
    }
}
This code checks that the TTS resource is successfully instantiated, then sets a US English Locale for the speech operations. You can optionally output an error message for users if the TTS does not successfully instantiate by adding the following after the “if” block:
1
2
3
else if (initStatus == TextToSpeech.ERROR) {
    Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
If you use this code you will also need to import the Toast class by adding the following statement at the top of your file:
1
import android.widget.Toast;
Your app can carry out checks on the user device, such as available languages, as in the following extended version of the statement creating the TTS object inside the first conditional statement:
1
if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE) myTTS.setLanguage(Locale.US);

Step 10: Speak!

Finally, your app is ready to speak. Inside the “speakWords” method, add the following code:
1
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
There are lots of options here in terms of how your app handles speech. This code instructs the app to speak the text string immediately. If you want to add consecutive speech operations, you can instruct the app to wait until any current speech operations finish by adding your new speech item to a queue, as follows:
1
myTTS.speak(speech, TextToSpeech.QUEUE_ADD, null);
Speaking User Text
Once your class is finished with the TTS, you can optionally shut it down as follows:
1
myTTS.shutdown();
Don’t include this line if you want your users to be able to make the app speak more than once.

Conclusion

To see how all of these elements fit together, here is the complete class declaration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.widget.Toast;
public class SpeakingAndroid extends Activity implements OnClickListener, OnInitListener {
        //TTS object
    private TextToSpeech myTTS;
        //status check code
    private int MY_DATA_CHECK_CODE = 0;
        //create the Activity
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                //get a reference to the button element listed in the XML layout
            Button speakButton = (Button)findViewById(R.id.speak);
                //listen for clicks
            speakButton.setOnClickListener(this);
            //check for TTS data
            Intent checkTTSIntent = new Intent();
            checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
            startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
    }
        //respond to button clicks
    public void onClick(View v) {
            //get the text entered
            EditText enteredText = (EditText)findViewById(R.id.enter);
            String words = enteredText.getText().toString();
            speakWords(words);
    }
        //speak the user text
    private void speakWords(String speech) {
            //speak straight away
            myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
    }
        //act on result of TTS data check
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                //the user has the necessary data - create the TTS
            myTTS = new TextToSpeech(this, this);
            }
            else {
                    //no data - install it now
                Intent installTTSIntent = new Intent();
                installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installTTSIntent);
            }
        }
    }
        //setup TTS
    public void onInit(int initStatus) {
            //check for successful instantiation
        if (initStatus == TextToSpeech.SUCCESS) {
            if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
                myTTS.setLanguage(Locale.US);
        }
        else if (initStatus == TextToSpeech.ERROR) {
            Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
        }
    }
}
Remember to use your own class name and to indicate your application package at the top of the file. If you are using Eclipse, you should not need to add all of the import statements manually, as the IDE will insert some of them automatically. Run your app in the Android emulator and hear it in action.
This is a basic overview of implementing Text To Speech in your Android apps. The TTS resource provides a wide range of additional options you may want to explore depending on the nature of your apps. When calling the TextToSpeech object “speak” method for example, you can pass a HashMap object indicating the details of more complex playback options.
Read More