Android Development: Passing Data Between Activities

Every thing you do in android is an instance of Activity class. The back button (mostly implemented in hardware - now also on software - Example Galaxy Tab 10.1 and ICS) allows to unload current activity and go back to previous one.

Lets say you are building a game and would like to pass data between your menu screen and the game screen. You show a bunch of options to the user in the menu screen and you have to pass the appropriate paramater to the Game Screen. Lets call our Activities GameActivity and MenuActivity

Loading a different GameActivity from MenuActivity:

First thing you need to understand is how to load a different activity from current activity. In order to do this, we use Intent class. Here is some code.


Intent intent=new Intent(view.getContext(),GameActivity.class);
startActivity(intent);

As you can see Intent class will load the class dynamically (reflection) and show you the new activity on the screen. Lets assume you created 3 buttons on the menu screen

  1. Easy
  2. Medium
  3. Hard

You have to pass a parameter to your GameActivity which level the user wants to play. Here is some code that will accomplish it.


Intent intent=new Intent(view.getContext(),GameActivity.class);
Bundle bundle=new Bundle();
bundle.putString("gameLevel","Easy");
intent.putExtras(bundle);
startActivity(intent);

You would repeat the same code above for different Game Level selections on your MenuActivity.

In the Game Activity you need to retrieve the passed bundle.


Bundle bundle=getIntent().getExtras();
String level=bundle.getString("gameLevel");
if(level.equals("Easy"){
...
}  
else if(level.equals("Medium")}
...
}      

You can pass various other types in a bundle. Check Android documentation at http://developer.android.com/reference/android/os/Bundle.html

Download Source for the sample project Below

Sample Project.

By: gavi on: