putExtras多个putString不工作 [英] putExtras multiple putString not working
问题描述
我需要从一个activitiy传递2个变量到另一个活动。
I need to pass 2 variables from one activitiy to another 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;
然后在我使用它来获取值回来了,但两个值,即相同的一样drinkType案例1我得到的第二个活动1这两个病例2我得到2既当我希望得到4,1和1,2。
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?
推荐答案
如果你不赋值给变量 drinkButton
和 drinkType
,他们都空
当你在第一个活动中使用它们。在这种情况下,你的code:
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");
等同于
bundle.putString(null, "4");
bundle.putString(null, "1");
你看,你使用的是与空
值作为钥匙的说法变量 putString()
。
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");
和在第二活动检索它们
String drinkButton = extras.getString(IntentConstants.EXTRA_DRINK_BUTTON);
String drinkType = extras.getString(IntentConstants.EXTRA_DRINK_Type);
顺便说一句,有没有你传递的整数值为String额外特别的原因?为什么不将它们作为整数?
By the way, is there a particular reason that you're passing integer values as String extras? Why not pass them as integers?
这篇关于putExtras多个putString不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!