I need to pass 2 variables from one activitiy to another activity.
I have the following for the first activity:
@Override
public boolean onContextItemSelected(MenuItem item) {
Bundle bundle=new Bundle();
switch (item.getItemId()){
case 1:
bundle.putString(drinkButton, "4");
bundle.putString(drinkType, "1");
Intent myIntent1 = new Intent(this, DrinksList.class);
myIntent1.putExtras(bundle);
startActivityForResult(myIntent1, 0);
return true;
case 2:
bundle.putString(drinkButton, "1");
bundle.putString(drinkType, "2");
Intent myIntent2 = new Intent(this, DrinksList.class);
myIntent2.putExtras(bundle);
startActivityForResult(myIntent2, 0);
return true;
}
return false;
Then in the second activity i use this to get the values back, but both values are the same i.e. the same as 'drinkType' case 1 I get "1" for both and case 2 I get "2" for both when I expect to get 4,1 and 1,2.
Bundle extras = getIntent().getExtras();
drinkButton = extras.getString(drinkButton);
drinkType = extras.getString(drinkType);
Toast.makeText(this, "drink Button = "+drinkButton+" Drink Type = "+drinkType, Toast.LENGTH_LONG).show();
}
It seems I can't pass more than one extra. Any ideas?
If you don't assign values to the variables drinkButton and drinkType, they're both null when you use them in the first activity. In that case, your code:
bundle.putString(drinkButton, "4");
bundle.putString(drinkType, "1");
is equivalent to
bundle.putString(null, "4");
bundle.putString(null, "1");
See, you're using variables with null value as the "key" argument to putString().
The most common way to set the "key" arguments like this is to use constants. For example:
public interface IntentConstants {
public static final String EXTRA_DRINK_BUTTON = "DrinkButton";
public static final String EXTRA_DRINK_TYPE = "DrinkType";
}
And then in your activity, use those constants, like this:
bundle.putString(IntentConstants.EXTRA_DRINK_BUTTON, "4");
bundle.putString(IntentConstants.EXTRA_DRINK_TYPE, "1");
and to retrieve them in the second Activity:
String drinkButton = extras.getString(IntentConstants.EXTRA_DRINK_BUTTON);
String drinkType = extras.getString(IntentConstants.EXTRA_DRINK_Type);
By the way, is there a particular reason that you're passing integer values as String extras? Why not pass them as integers?
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