Wednesday, October 13, 2010

Using Intent and Bundle to pass String values to a new Activity.

So it took me three days to figure out how to pass on a string value from an old activity to a new one. This version uses bundle and intent.

I have only used this when starting a new activity with a button , list item , and menu item clicks events, although I'm sure it can be applied to many more types. 

You will need two activities. My example uses a list item click to set up a regular intent. A bundle is created with a string value, and its variables are ("unique.key.name", "The string you want to pass on"). (items[position]) is code that displays the text value of the list item that was selected. Then the bundle is added to the intent.

Page1.java
public void onListItemClick(ListView parent, View view, int position, long id) {
     Intent i = new Intent(Page1.this, Page2.class);
Bundle extras = new Bundle();
extras.putString("my.unique.extras.key", (items[position]) + " Details");
i.putExtras(extras);                
startActivity(i);
    }

Page2 activity needs to have a textview item ready to receive the bundle (this would look like uniquetextview.setText(extras.getString("("my.unique.extras.key")). An alternative is to set the bundle to be the activities title, as in my example below.

Page2.java

  // Adds selected listview item to title
        Bundle extras = this.getIntent().getExtras();
if ( extras != null ) {
 if ( extras.containsKey("my.unique.extras.key") ) {
 this.setTitle(extras.getString("my.unique.extras.key"));
 }
}

No comments:

Post a Comment