Home > Android, Android how to > Passing data between activities in Android

Passing data between activities in Android


We moved. Please visit this link for this post.

 

 

 

In Android is simple to run one activity from other. But what if you need to send data to the new activity. You can use several ways, for example DB, preferences, file system or just use Bundle. Last one is very useful in practice and I will show how to do this .

For this operation need 2 classes.

At first Intent

At second Bundle

Example:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();

b.putInt("key", 1);

intent.putExtras(b);

startActivity(intent);

finish();

There are 2 method which are interesting.

First method is

b.putInt("value", 1);

This method puts in Bundle key “key” and its value 1. Bundle class has a lof of put* methods.

Second method is:

intent.putExtras(b);

This method puts our bundle in Intent which starts new activity.

Now need to get passed data on new SecondActivity.

This process is also simple

Bundle b = getIntent().getExtras();

int value = b.getInt("key", 0);

First method gets needed Bundle.

Second method gets our data. As you can see there is second parameter “0″. It is default value. In situation when Bundle doesn’t contains data you will receive “0″ (default value).

I hope it was useful for you.

About these ads
Categories: Android, Android how to
  1. Rui Gonçalves
    December 4, 2009 at 2:36 am

    Hi there!

    Your post was very useful for me, thank you.

    Best regards,
    Rui

  2. Divya
    April 23, 2010 at 4:14 am

    Thankyou

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: