无法将整数值传递给第二个Activity

时间:2012-11-06 20:38:46

标签: android int android-activity bundler

我从第一个开始调用第二个活动:

Intent intent = new Intent();
intent.setClass(MainActivity.this,  SecondActivity.class);
Bundle b = new Bundle();
b.putInt(SecondActivity.ID,id);
System.out.println("id*"+id);
b.putString(SecondActivity.NAME, name);
System.out.println("name*"+name);
intent.putExtras(b);
startActivity(intent);

logcat的:

11-06 19:33:57.451: I/System.out(7987): id*2
11-06 19:33:57.451: I/System.out(7987): name*MrBlack

第二项活动:

public static final String ID = "";
public static final String NAME = "";
................
Bundle extras = getIntent().getExtras();
int id = extras.getInt(ID);

System.out.println("extras.getInt(ID)*"+extras.getInt(ID));
System.out.println("extras.getString(ID)*"+extras.getString(ID));
System.out.println("extras.getString(NAME)*"+extras.getString(NAME));
TextView tvFirmaName = (TextView) findViewById(R.id.tvName);
tvFirmaName.setText(extras.getString(NAME));

logcat的:

11-06 19:33:57.721: I/System.out(7987): extras.getInt(ID)*0
11-06 19:33:57.731: I/System.out(7987): extras.getString(ID)*MrBlack
11-06 19:33:57.731: I/System.out(7987): extras.getString(NAME)*MrBlack

我不明白为什么int值2传递为0 为什么extras.getString(ID)是“MrBlack”值!?

请让我知道我错在哪里..

2 个答案:

答案 0 :(得分:4)

public static final String ID = "";
public static final String NAME = "";

您需要为这些字符串提供值,它们充当您传递的信息的变量名称。只要它们彼此不相等,它们的价值就是任意的。

干杯

答案 1 :(得分:1)

extras就像hashmaps一样工作。所以你必须这样做:

b.putInt("unique key","value");

因为您使用空字符串作为键,所以它返回带有“”键的第一个...

所以尝试输入如下值:

b.putInt("ID",id);
b.putInt("NAME",name);