Passing a Bundle on startActivity()?
What's the correct way to pass a bundle to the activity that is being launched from the current one? Shared properties?
Solution 1:
You have a few options:
1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
Then, in the launched Activity, you would read them via:
String value = getIntent().getExtras().getString(key)
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
Solution 2:
You can use the Bundle from the Intent:
Bundle extras = myIntent.getExtras();
extras.put*(info);
Or an entire bundle:
myIntent.putExtras(myBundle);
Is this what you're looking for?
Solution 3:
Passing data from one Activity to Activity in android
An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra()
method. Data is passed as extras and are key/value pairs
. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable
objects from one activity to other.
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);
Retrieving bundle data from android activity
You can retrieve the information using getData()
methods on the Intent object. The Intent object can be retrieved via the getIntent()
method.
Intent intent = getIntent();
if (null != intent) { //Null Checking
String StrData= intent.getStringExtra(KEY);
int NoOfData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue);
}
Solution 4:
You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.
Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);
Now in your NewActivity, you can get this bundle and retrive your value.
Bundle bundle = getArguments();
String value = bundle.getString(key);
You can also pass data through the intent. In your current activity, set intent like this,
Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);
Now in your NewActivity, you can get that value from intent like this,
String value = getIntent().getExtras().getString(key);