6 Oct 2014

Switch between Activities in Android

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.

Lets assume that our new Activity class name is SecondActivity.java

Opening new Activity

To open new activity following method will be used :- startActivity() or startActivityForResult() 
Intent i = new Intent(getApplicationContext(), SecondActivity.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 username to next screen as
// Key = 'username'
// value = 'Amardeep'
i.putExtra("username", "Amardeep");
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 'username'
// and storing the value in a variable named myname
String myname = i.getStringExtra("username");
Opening new Activity and expecting result
In some situations you might expect some data back from newly created activity. In that situationsstartActivityForResult() method is useful. And once new activity is closed you should you useonActivityResult() method to read the returned result.
Intent i = new Intent(getApplicationContext(), SecondActivity.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 'email' and value as 'amardeepvijay00@gmail.com'
i.putExtra("email", "amardeepvijay00@gmail.com");
// 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 tags.
<activity android:name=".NewActivityClassName"></activity>

Read More !