Sunday, December 25, 2011

Android Tutorial Part 4 - Using Intents for passing data from one activity to other


Earlier we navigated from one activity to other. Now we will check how to pass data from one activity to other.

You may remember how we navigated to the second activity.

public void goToMyNextActivity(View view) {
        Intent myIntent;
        myIntent = new Intent(this, SecondActivity.class);
        startActivity(myIntent);
    }


To pass data we need to add the data as a bundle extra, to the object we created. You can pass any type of data as a *key value pair. Here I'm going to pass a string and an int.

public void goToMyNextActivity(View view) {
        Intent myIntent;
        myIntent = new Intent(this, SecondActivity.class);
        myIntent.putExtra("name", "Tom");
        myIntent.putExtra("age", 25);
        startActivity(myIntent);
       
    }


Take a look at

myIntent.putExtra("name", "Tom");

Here 'name' is my key and 'Tom' is the value. In the next line 'age' is the key and '25' is the value.

Now we will move to the onCreate function of the next activity(SecondActivity). To retrieve the above values I have to refer the corresponding keys used. Check the following code:

String name = getIntent().getStringExtra("name");
int age = getIntent().getIntExtra("age", 0);

In getting some data types from an intent you have to define a default value also. That's why in the second line while getting the int value I had defined the defalt value as 0. So due to some reason if you forgot to pass the value for 'age' then it will take the default  value. You can set the default value as you like.

To check whether the data has reached the second activity, here I'm going to use the Logcat. On my last post I told you how to access the Logcat.

To print some thing in the log you have to use the following syntax

Log.<debugging level> (String tag, String  message);

debugging level: Based upon the level of debugging you can use i(INFO), e(ERROR), d(DEBUG), v(VERBOSE) etc.

tag: Used to identify the source of a log message. It usually identifies the class or activity where the log call occurs.

message: The message you would like logged.

Here I'm going to use INFO level logs.

Log.i("NAME", ""+name);
Log.i("AGE", ""+age); 


Ir's time to text our code. From the first screen tap the 'Next Activity' button. You will reach the next screen now check the Logcat.



Now in the first activity(Sample2Activity) where we created an object for Intent remove the following line and check logcat.

myIntent.putExtra("age", 25);

You can see the default value in the logcat!














































*key value pair - Each value will be stored against a key. To retrieve the value you have to refer that key