Pages

Tuesday 14 June 2011

First Steps - Passing values to an Activity

How do I pass a value to an activity?

To start an Activity you use an Intent. In this intent you can pass data which is returned as a Bundle object.

Android Activities and Intents

Below is some simple example code for creating a new intent to launch an Activity named MyActivity. Note the call to the putExtra method which accepts a key name ("content") and a value:

Intent myIntent = new Intent();
String packageName = this.getPackageName();
myIntent.setClassName(packageName,
packageName + "." + MyActivity.class.getSimpleName());
myIntent.putExtra("content", "my content string");
startActivity(myIntent);

Here is the code for the called activity with the Bundle data extracted from the intent. You can then retrieve the passed extra content from the bundle object:

public class MyActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contentweb);

    Bundle bundle = getIntent().getExtras();
    String content = bundle.getString("content");
  }
}

All pretty simple when you know how.

0 comments:

Post a Comment