我想将活动中的值传递给另一个活动并使用此代码
Intent i = new Intent(MainActivity.this,ListActivity.class);
i.putExtra("position","ایران");
startActivity(i);
并且在return变量的其他活动中使用此代码
value = getIntent().getExtras().getString("position");
现在,当我运行该程序时,它会出现此错误:
java.lang.nullpointerexception
请帮帮我。
答案 0 :(得分:1)
这是检索字符串额外的正确方法:
value = getIntent().getStringExtra("position");
<强>解释强>
为什么getExtras()不起作用: getExtras()返回一个先前使用putExtras(bundle)放入intent中的bundle。 所以,代码看起来像:
// Put position inside intent using extras:
Intent intent = new Intent();
Bundle extras = new Bundle();
extras.putString("position",position);
intent.putExtras(extras);
// Retrieve position:
getIntent().getExtras().getString("position");
但这是更多的代码,直接在意图中存储额外的更简洁的方式