Feeds:
Posts
Comments

I was trying to google some resources on Pending Intent flags but couldn’t find a good explanation, so thought of writing the same. This blog explains the flags needed for creating Pending Intent.
The following example uses Pending Intent object for creating a notification.
What is Pending Intent– Pending Intent is used to grant other application the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent: often, for example, the base Intent you supply will have the component name explicitly set to one of your own components, to ensure it is ultimately sent there and nowhere else.
PendingIntent can be created as follows:
PendingIntent pi= PendingIntent.getActivity(Context context, int requestCode, Intent intent, int flags)
The above line of code retrieves a PendingIntent that will start a new activity, like calling Context.startActivity(Intent).
The last argument is the PendingIntent flag. The flags can take any of the following values:
FLAG_CANCEL_CURRENT -Flag for use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int): if the described PendingIntent already exists, the current one is canceled before generating a new one.
FLAG_NO_CREATE-Flag for use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int): if the described PendingIntent does not already exist, then simply return null instead of creating it.
FLAG_ONE_SHOT-Flag for use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int): this PendingIntent can only be used once.
FLAG_UPDATE_CURRENT-Flag for use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int): if the described PendingIntent already exists, then keep it but its replace its extra data with what is in this new Intent.
Example-The code below explains the concept of Pending Intent flags. The results obtained by running the same code with different flags ,are mentioned below :

package com.ls.la;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class NotificationProjActivity extends Activity {

	NotificationManager nm;
	Notification notification;

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

		Intent notificationIntent = new Intent(this, MyClass.class);
		String n = Context.NOTIFICATION_SERVICE;
		nm = (NotificationManager) getSystemService(n);
		int icon = R.drawable.icon; // icon from resources
		String tickerText = "Hello"; // ticker-text
		long when = System.currentTimeMillis(); // notification time
		Context context = getApplicationContext(); // application Context
		CharSequence contentTitle = "My notification"; // expanded message title
		CharSequence contentText = "Hello World!"; // expanded message text

		notificationIntent.putExtra("n1", 30);
		notificationIntent.putExtra("n2", "test");

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);

		// the next two lines initialize the Notification, using the
		// configurations above
		notification = new Notification(icon, tickerText, when);
		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent);
		notification.defaults = Notification.DEFAULT_SOUND
				| Notification.DEFAULT_VIBRATE;
		// long[] vibrate = { 0, 100, 200, 300 };
		// notification.vibrate = vibrate;
		notification.flags = Notification.FLAG_AUTO_CANCEL;

		nm.notify(1, notification);

		notificationIntent.putExtra("n1", 80);
		
		//creating 2nd Pending Intent with the matching intent and  		//using flag FLAG_NO_CREATE

		PendingIntent contentIntent1 = PendingIntent.getActivity(this, 0,
				notificationIntent, PendingIntent.FLAG_NO_CREATE);

		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent1);
		notification.defaults = Notification.DEFAULT_SOUND
				| Notification.DEFAULT_VIBRATE;
		notification.flags = Notification.FLAG_AUTO_CANCEL;

		// for logging if the new pending intent created is same object or not

		if (contentIntent.equals(contentIntent1)) {

			Log.v("NotificationProjActivity", "OBJECTS ARE EQUAL");

		} else {
			Log.v("NotificationProjActivity", "OBJECTS ARE NOT EQUAL");

		}

		nm.notify(1, notification);

	
	}
}

In the above code a Pending Intent object contentIntent is created as follows:


 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);

The notificationIntent is an Intent object having one integer extra and one String extra.


		notificationIntent.putExtra("n1", 30);
		notificationIntent.putExtra("n2", "test");

Then a second PendingIntent is created using the same matching Intent as follows:


PendingIntent contentIntent1 = PendingIntent.getActivity(this, 0,
				notificationIntent, PendingIntent.FLAG_NO_CREATE);

However, a couple of points to mention here:
1. The same matching intent notificationIntent is used but the integer extra has been changed from 30 to 80.
notificationIntent.putExtra(“n1”, 80);
2. The PendingIntent flag FLAG_NO_CREATE is used for the 2nd PendingIntent contentIntent1.
Lastly, a log statement has been used in the code to check if the PendingIntent contentIntent and PendingIntent contentIntent1 are equal or not.


if (contentIntent.equals(contentIntent1)) {

			Log.v("NotificationProjActivity", "OBJECTS ARE EQUAL");

		} else {
			Log.v("NotificationProjActivity", "OBJECTS ARE NOT EQUAL");

		}

FLAG_NO_CREATE-
If, we run the above code, we will see that the Log message will print :
OBJECTS ARE EQUAL.
Also, when we retrieve the intent in MyClass (which will happen when we click on the notification from the notification tray), the values of integer extra will be 30 and not 80.
The above clearly explains that if there is an existing PendingIntent object which matches and the FLAG_NO_CREATE is specified then a factory method will return a PendingIntent instance which refers to the existing PendingIntent object.If this flag is specified a new PendingIntent instance will not be created.This can be verified by the log message and the integer extra.

FLAG_UPDATE_CURRENT-
Now run the above code, by changing the flag from FLAG_NO_CREATE to FLAG_UPDATE_CURRENT
When we run the code after changing the flag, we will see that the Log message will print :
OBJECTS ARE EQUAL.
Also, when we retrieve the intent in MyClass (which will happen when we click on the notification from the notification tray), the values of integer extra will be 80 and not 30.If FLAG_UPDATE_CURRENT flag is specified and a matching PendingIntent exists then it will be updated with the new extra value if any. This can be verified by the log message and the integer extra.

FLAG_CANCEL_CURRENT-
Now run the above Now run the above code, by changing the flag from FLAG_UPDATE_CURRENT to FLAG_CANCEL_CURRENT
When we run the code after changing the flag, we will see that the Log message will print :
OBJECTS ARE NOT EQUAL.
Also, when we retrieve the intent in MyClass (which will happen when we click on the notification from the notification tray), the values of integer extra will be 80.If this flag is specified and a matching PendingIntent exists then it is cancelled.

I have posted the source code of the PendingIntent flags at :

Download source code (NotificationProj.rar)

au revoir. profiter le blog (Bye. Enjoy the blog)

During one of the training programs someone asked me how to query the MediaStore database for images. So, i thought of writing a small program for the same.

The database or Content URI for the Images is MediaStore.Images.Media.EXTERNAL_CONTENT_URI .
This is the content:// style URI for the “primary” external storage volume.
The querying method is same like querying any other native content provider.
First obtain the ContentResolver object by using getContentResolver();
We can then query the contentresolver object as follows:


Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				
                         null, null, null, null);

The Images DataStore has a couple of columns. Some of the main columns are:
1.MediaStore.Images.ImageColumns._ID– This represent the Unique ID of the row.
2.MediaStore.Images.Media.DATE_TAKE– The date when the image was captured. The same is in long miliseconds.
3.MediaStore.Images.Media.LATITUDE– The latitude where the image was captured.
4.MediaStore.Images.Media.LONGITUDE– The longitude where the image was captured.
5.MediaStore.Images.Media.DESCRIPTION-The description of the image
For example, if we want to get the date of the image taken, then we would iterate the cursor and query the date column as follows:


String date = cursor.getString(cursor
						.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));

A major point to remember here is that when we are working with bitmaps , if we do not recycle them then we might see OutOfMemory issues such as OutOfMemoryError: bitmap size exceeds VM budget.
To avoid memory leaks remember to unbind the drawables and recycle the bitmaps in Activity onDestroy method. (REF:Avoid MemoryLeak)

I have posted the source code of the QueryMedia at :

Download source code

Browse Source code:

The same queries the SDcard for all the images stored in it and display them in the gridview along with the date they were captured.
If you are running this code on emulator please ensure that you have some images in your emulator sdcard.

In this blog we will discuss how to query the Android Package Manager.

Package Manager Class is used for retrieving various kinds of information related to the application packages that are currently installed on the device. It can be queried to find out what all applications are installed, what are the main Activities for these applications, their permissions etc.

So, let us say if we want to know the name of all the applications installed on our device with their main activity classes name, this can be done as follows.

// get the package manager object
		PackageManager pm = getPackageManager();
		// create an Intent with ACTION_MAIN and CATEGORY LAUNCHER
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

		// query the package manager for the desired intent
		// obtain the list of ResolveInfo objects
		List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);
		for (ResolveInfo resolveInfo : list) {

			ActivityInfo activityInfo = resolveInfo.activityInfo;

			// get the name of the Main activity class
			String activityName = activityInfo.name;

			ApplicationInfo applicationInfo = activityInfo.applicationInfo;
			// get the name of the application class
			String applicationName = applicationInfo.className;

			if (applicationName != null) {
				Log.v("APP_NAME", applicationName);

			}

			if (activityName != null) {
				Log.v("ACTIVITY_NAME", activityName);
			}
		}

The ContextWrapper class has a method getPackageManager() which returns the PackageManager Object. On this pacakge manager object we can call the method queryIntentActivities. This method retrieve all activities that can be performed for the given intent.

queryIntentActivities takes 2 argumennts.
Intent– The desired intent as per resolveActivity().
flags– Additional option flags. The most important is MATCH_DEFAULT_ONLY, to limit the resolution to only those activities that support the CATEGORY_DEFAULT.
Returns-This method returns the list of ResolveInfo objects containing one entry for each matching Activity

In our example, we have created an Intent object with ACTION_MAIN and Intent.CATEGORY_LAUNCHER as we are interested in getting a list of all the applications which are listed in the launcher screen.
Once we obtain the list the same is iterated to get the application names and their main activity names.

I also conduct Android training on weekends in Gurgaon at Cwide. Visit http://www.cwide.in for more details.

Details of the course:
This Android course is a interactive, hands-on training which provides you a complete overview of the Android platform and how to make the most of your application development.
The curriculum is developed according to industry standards and requirements and this course will make you an expert by leveraging your existing Java skills
You will be trained with original Android Phones and Tablets to test your application.
At the end of the course, you will have the knowledge to build and publish your own real-time Android application

One of the prerequisite for Android is that you need to have java background.
If you do not know java and want to learn Android, you can take the basic core java course from me.

Android COURSE FEES- 12000 .
If you are interested in learning development of apps for Honeycomb then the course fees is INR 14,000. (The Honeycomb course content is also attached with the phone apps development course content).

You can opt for either the weekend batch – Both Saturday and Sunday. Duration 5 weekends. (10 classes) Timings 11.30 a.m.-6.00 p.m. Timings are flexible.
Or you can opt for weekdays classes. Duration 20 days . Timings- 9.00a.m. to 12.00 p.m. Timings are flexible.

Interested candidates call at 9560597070 or mail at androidtraining4u@gmail.com

Explanation with sample codes and small programs for each and every topic. At the end of the course you will be given a sample project which will help you in integrating all the concepts learnt by you.

About the trainer:
I am a freelancer android developer and corporate trainer having 2 years of experience in android and 3.5 years of experience in Java.

My app published in the market are:
Future Teller Ram Prashnavalli

Some other apps developed by me :

COURSE CONTENTS:

Module I

Getting started with android
Android Features
Android Architecture
Android Application fundamentals

Module II
Creating an Activity
Declaring the activity in the manifest
Starting an Activity
Starting an activity for a result
Shutting Down an Activity
Managing the Activity Lifecycle
Implementing the lifecycle callbacks
Saving activity state
Handling configuration changes

Module III
UI design
Components and layouts- Frame Layout, Linear Layout, Relative Layout
Write the XML
Load the XML Resource
Attributes- ID, Layout Parameters,Position, Size, Padding and Margins

Module IV
Working with resources- String resource, Color resource, Array resource
Android layouts and views
Handling user interaction events
Grouping, accessing of resources
Localization of Resources
Handling runtime changes of resources
Designing your GUI

Module V
Implicit Intent
Overview (Action, Data, category, etc)
How intent works
How intent filter works and writing our own intent filters

Module VI
Creating menus- Options Menu. Context Menu
Styles and themes
Creating dialogs- Alert Dialog, DatePicker Dialog, TimePicker Dialog, Progress Dialog

Module VII
Notifying the users- Toast Notifcation, Status Bar Notifcation
Debugging android applications
Broadcast Recievers

Module VIII
Binding to Data with AdapterView
List View- Simple List, Cutom List
Spinner
GridView
Sliding Drawer View, Rating Bar View, Toggle Button View

Module IX
Multimedia in android
Simple media playback from Local file system
Media playback from URL
Media Playback from raw folder
Play Video from local file system
Play video from URL

Module X
Data Storage
Using Shared Preferences
Using the Internal Storage
Using the External Storage

Module XI
Using Databases
Sqlite open helper and creating a database
Opening and closing a database

Module XII
Basic content providers
CRUD operation on Contacts Database
CRUD operations on IMAGE Database
Creating your own DB for your Application

Module XIII
Graphics and Animations
View Animation- Tween animation, Frame Animation
Drawable Animation- Nine-Patch File, State List, Transition Drawable

Module XIV
Mutithreading in Android
Asynch Task

Module XV
Accessing android hardware
Using the camera
Using bluetooth
Using Wifi

Module XVI
Geocoding and Location Based Services
Maps
Finding Current Location
Using Geocoder to get the current address of the user
Plotting the current location on map

Module XVII
Telephony and SMS

Module XVIII
Sensors
Accelerometer Sensor
Proximity Sensor
Light Sensor

Module XIX
Web services
Parsing JSON data
Parsing XML data- Simple API XML Parser and DOM Parser

Module XX
Service
Creating a Started Service
Creating a Bound Service

Module XXI
Honeycomb Fragments
Dialog Fragment
Action Bar
Tabbed Navigation Action Bar Activity
List Navigation Action Bar Activity

How to pass user defined Object from one activity to other

In the previous blog we saw how to pass the primitive data from one activity to other. In this blog we’ll see how we can pass user defined data from one activity to other. Let us say we have a user defined class Employee having two attributes id and name. In order to enable us to pass object of Employee from 1 activity to other the Employee class needs to implement the interface called Parcelable. This interface is for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface.

Employee.java


package com.passdata;

import android.os.Parcel;
import android.os.Parcelable;

public class Employee implements Parcelable {
	int id;
	String name;
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		dest.writeInt(id);
		dest.writeString(name);

	}

	public Employee(Parcel source) {
		// TODO Auto-generated method stub
		id = source.readInt();
		name = source.readString();

	}

	public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {

		@Override
		public Employee createFromParcel(Parcel source) {
			// TODO Auto-generated method stub
			return new Employee(source);
		}

		@Override
		public Employee[] newArray(int size) {
			// TODO Auto-generated method stub
			return new Employee[size];
		}
	};

}

When a class implements Parcelable interface it needs to override 2 methods – describeContents method and writeToParcel method. writeToParcel method is overriden to flatten this object in to a Parcel. In our overriden method of Employee class we are just writing the id and name attribute of Employee object into Parcelable object. Also, classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface. So in our Employee class we are making a static field CREATOR. We need to override 2 methods here:
1. createFromParcel(Parcel source)
Create a new instance of the Parcelable class, instantiating it from the given Parcel whose data had previously been written by Parcelable.writeToParcel().
2.newArray(int size)
Create a new array of the Parcelable class.
As our overriden version of createFromParcel returns a new Employee object by calling constructor of Employee with Parcelable object as argument we need to create a constructor in Employee class for the same.

public Employee(Parcel source) {
// TODO Auto-generated method stub
id = source.readInt();
name = source.readString();

}
Once the above is done, we can create the Activity class as follows:

ActivityOne.java


package com.passdata;

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

public class ActivityOne extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button button = (Button) findViewById(R.id.btn);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(ActivityOne.this,ActivityTwo.class);
				Bundle b = new Bundle();
				Employee e = new Employee(1, "shawn");
				b.putParcelable("parse", e);
				intent.putExtras(b);
				startActivity(intent);
			}
		});
	}
}

ActivityTwo.java


package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityTwo extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity2);
		TextView textView = (TextView) findViewById(R.id.txt);
		Intent intent = getIntent();
		Bundle b = intent.getExtras();
		Employee e = b.getParcelable("parse");

		textView.setText(e.getId() + ":" + e.getName());
	}

}

The layout xml files are as follows:
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"
    >
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Pass Data"
    android:id="@+id/btn"
    />
</LinearLayout>

activity2.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView
  
   android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/txt"
   />
    
</LinearLayout>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.passdata"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ActivityOne"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="ActivityTwo"></activity>

    </application>
</manifest>

Do let me know your feedback.

How to pass collection of primitive data types  from one activity to other

Objects can also be passed from one activity to other by packaging them in a Bundle object.
In the example below we are packaging a string object and a string array in a Bundle Object and passing it to Activity2. All the xml files strings.xml,main.xml,activity2.xml,AndroidManifest.xml are same as Part1 of blog- Android Intents for Passing Data between Activities-Part1

ActivityOne.java

package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ActivityOne extends Activity {
EditText editText;
Button button;
final String[] arr = new String[] { "one", "two", "three" };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.main);

editText= (EditText) findViewById(R.id.edit1);
button = (Button) findViewById(R.id.btn);

/** setting the onclick listener for button */
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

/** getting the value of edit text entered by user */
String textVal = editText.getText().toString();
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);

/** setting the textVal in intentExtra */
/** passing string */
Bundle b = new Bundle();
b.putString("name", textVal);

/** passing string array*/
b.putStringArray("array", arr);
intent.putExtras(b);

/** start Activity2 */
startActivity(intent);
}
});

}
}

In the above example the Bundle object b is created by calling the constructor of Bundle object. In the bundle object string is passed by calling putString with the key and value parameters. Similarly, boolean, float, long etc can be passed. In the above code we are also passing string array by calling putStringArray(“array”, arr) on bundle object. Finally, the bundle object is set in intent.

Retrieve data passed in ActivityTwo:

package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityTwo extends Activity {

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.activity2);
textView = (TextView) findViewById(R.id.txt2);
/** get the intent */
Intent intent = getIntent();

/** get the bundle from intent*/
Bundle b = intent.getExtras();
/** retrieve the string extra passed */
String a = b.getString("name");

/** retrieve the stringarray extra passed */
String[] arrRecd = b.getStringArray("array");
textView.setText(a + ":val:" + arrRecd[1]);
}

}

To retrieve the data passed in intent first we get the intent object. The activity class has method called getIntent() that returns the intent object that started this activity. Once we have the intent object  we can use getExtras to get the bundle object.Then on the  bundle object we can call getString to get the string type passed in the intent. This method takes the string argument which is the key used when we set the data in intent object in ActivityOne.

In the last part of this post we will see

How to pass user defined Object from one activity to other

This blog is covered in 3 parts. It will help you in understanding the following:
1. How to pass primitive data type from one activity to other
2. How to pass collection of primitive data types  from one activity to other
3. How to pass user defined objects from one activity to other

The first part covers

How to pass primitive data from one Activity to other.

In Android to pass data from one Activity to other we use Intent class objects. Intents can be thought of mechanism to pass objects between activity or broadcast reciver or services.
Example:
Let us say we have an acivity, ActivityOne which has a  TextView and a Button. The user enters some text in the text box and clicks on the Button. The click event will redirect the user to the next Activity, ActivityTwo. ActivityTwo displays a customised welcome message to the user with the text entered by user in ActivityOne. We have to pass the text entered by the user in ActivityOne to ActivityTwo. This can be achieved by creating Intent Object.

ActivityOne .java


package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ActivityOne extends Activity {
EditText editText;
Button button;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.main);

editText= (EditText) findViewById(R.id.edit1);
button= (Button) findViewById(R.id.btn);

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

/** getting the value of edit text entered by user */
final String textVal = editText.getText().toString();

Intent intent = new Intent(ActivityOne.this,
ActivityTwo.class);

/** setting the textVal in intentExtra */
intent.putExtra("name", textVal);
intent.putExtra("testBool", true);

startActivity(intent);
}
});

}
}

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"
>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edit1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="@string/buttonText"

/>
</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ActivityPassDataActivity!</string>
    <string name="app_name">ActivityPassData</string>
    <string name="buttonText">Pass Data</string>
</resources>

In the button onClickListener we are creating an Intent object. The Intent object takes 2 arguments. First argument is the context and second is the Class to which the intent is passed. In this example we are passing the intent to ActivityTwo, so we are setting the class as ActivityTwo.class. The Intent object has a public method putExtra. This method takes 2 arguments. The first argument is the key and 2nd argument is the value for that key.  The 2nd argument can be of any type boolean , float, double, long etc. For example, if we have to pass boolean we can use i.putExtra(“test”, true);

Retrieve data passed in ActivityTwo:

ActivityTwo.java

package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityTwo extends Activity {

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.activity2);
textView = (TextView) findViewById(R.id.txt2);

/**get the intent*/
Intent intent = getIntent();

/**retrieve the string extra passed*/
String stringRecd = intent.getStringExtra("name");

/*retrieve the boolean extra passed*/
Boolean boolRecd = intent.getBooleanExtra("testBool", false);
textView.setText(stringRecd + ":boolval:"+boolRecd );
}

}

activity2.xml


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

<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/txt2"
android:layout_marginTop="30sp"
android:gravity="center"
/>

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.passdata"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ActivityOne"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="ActivityTwo"></activity>

    </application>
</manifest>

To retreive the data passed in intent first we get the intent object. The activity class has method called getIntent() that returns the intent object that started this activity. Once we have the intent object  we can use getStringExtra or getBooleanExtra or getFloatExtra depending on the data type passed in intent. In the above example to get the string type passed in the intent we used getStringExtra. This method takes the string argument which is the key used when we set the data in intent object in ActivityOne. In the method intent.getBooleanExtra(“testBool”, false), the second argument is the defaultValue to be returned if no value of the desired type is stored with the given name.

In the next post we will see

How to pass collection of primitive data types  from one activity to other