putExtras multiple putString not working

微笑、不失礼 提交于 2019-12-14 02:05:03

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/9241646/putextras-multiple-putstring-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!