Simple example for Intent and Bundle

Akshay Sethi picture Akshay Sethi · Feb 14, 2013 · Viewed 140.3k times · Source

I'm new to android with almost no knowledge about Java and XML. I'm learning it through pdfs that i'm getting on net. I have learnt about Toast, a bit about Intents but me not able to understand anything about Bundles. I have understood that they are used to pass data from one activity to another but I'm not able to implement this.

please give a simple example to implement the same.

as for example I have just created two activities namely , Main_Activity and Other_Activity, and i haven't done anything to them yet.

Please give the simplest example so that i can learn to implement.

Thanks in advance!!

Answer

Dany Pop picture Dany Pop · Feb 14, 2013

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html