Sunday, April 29, 2012

Android: Passing Values Between Activities with Bundle

This example uses the same layout as the previous example which shows how to open a second activity. There only difference in the layout is that I added two TextView controls to the Confirm.xml.

I am not going to repeat all the code and layout of the previous example. I am only going to focus on the code where it changes.

To transfer the values from the EditText controls on the first activity, I added a Bundle object. A Bundle object is essentially a hash control that stores key value pairs. I create the bundle in the first Activity, in the private class which implements the onClick event. I create the bundle, then add the values using the putString() method. Finally, I must declare and instantiate the new Activity differently than I did before in order to add the bundle with the putExtras() method

Here is the modified code:


 private class ConfirmClickListener implements View.OnClickListener{
     
     public void onClick(View v){
      //get the Edit text controls and their text value
      EditText nameText=(EditText)findViewById(R.id.editTextName);
      String fullName=nameText.getText().toString();
      
      EditText emailText=(EditText)findViewById(R.id.editTextEmail);
      String email=emailText.getText().toString();
      
      //create a bundle object to store the values
      Bundle bundle = new Bundle();
      //assign the values (key, value pairs)
      bundle.putString("name", fullName);
      bundle.putString("email", email);
      
      //create the intent
      //this is different than we did it before
      Intent i = new Intent(MultiActivityExampleActivity.this, Confirmation.class);
      //assign the bundle to the intent
      i.putExtras(bundle);
      //start the new activity
      startActivity(i);
     }
    }

Now here is the code on the Confirmation side. It declares a Bundle object and assigns its value from the getExtras() method. It extracts the values using the keys and then assigns them the TextView.


 public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.confirm);
  
  //create a bundle object to store
  //the bundle we added to the intent
  Bundle bundle=getIntent().getExtras();
  
  //get the values out by key
  String name=bundle.getString("name");
  String email=bundle.getString("email");
  
  //get the textview controls
  TextView txtName=(TextView)findViewById(R.id.textView2);
  TextView txtEmail=(TextView)findViewById(R.id.textView3);
  
  //set the text values of the text controls
  txtName.setText(name);
  txtEmail.setText(email);
  
 }

Now when you click on the comfirm button it passes the values from the first Activity to the second

2 comments: