Simple example for Intent and Bundle [duplicate]
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!!
Solution 1:
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
Solution 2:
Try this: if you need pass values between the activities you use this...
This is code for Main_Activity put the values to intent
String name="aaaa";
Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
intent.putExtra("name", name);
startActivity(intent);
This code for Other_Activity and get the values form intent
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
Solution 3:
Basically this is what you need to do:
in the first activity:
Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);
and in the second activtiy:
Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);
one of the get-functions will give return you the value, depending on the datatype you are passing through.