Android Intent Put Extra

Web Hosting
In Android user interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.

Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java
Opening new Activity
To open new activity following startActivity() or startActivityForResult() method will be used.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);

Sending parameters to new Activity
To send parameter to newly created activity putExtra() methos will be used.
i.putExtra("key", "value");
 
// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");

Receiving parameters on new Activity
To receive parameters on newly created activity getStringExtra() method will be used.
Intent i = getIntent();
i.getStringExtra("key");
 
// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");

Opening new Activity and expecting result
In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
 
// Function to read the result from newly created activity
@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
 
             // Storing result in a variable called myvar
             // get("website") 'website' is the key value result data
             String mywebsite = data.getExtras().get("result");
        }
 
    }

Sending result back to old activity when StartActivityForResult() is used
Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");
 
// Setting resultCode to 100 to identify on old activity
setResult(100,in);

Closing Activity
To close activity call finish() method
finish();

Add entry in AndroidManifest.xml
To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags
<activity android:name=".NewActivityClassName"></activity>


Web Hosting

No comments:

Post a Comment