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!!
An intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver,start services and send message between two activities. There are two intents available in android as Implicit Intents and Explicit Intents. Here is a sample example to start new activity with old activity.
Bundles are used with intent and values are sent and retrieved in the same fashion, as it is done in the case of Intent. It depends on the user what type of values the user wants to pass, but bundles can hold all types of values (int, String, boolean, char) and pass them to the new activity.
PutExtra() - we can store any primitive data type directly with (key,value) pair. And PutExtras() - hold object of Bundle class object . Bundle class provide us method of specific primitive data type methods to store data in it.
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
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With