我对android编程很新..我有这个问题..我想传递一个值,但结果是null ..我想知道为什么会这样..谁能帮助我?提前致谢。我的代码是这样的..
Manager.java
String prize="5";
Intent i = new Intent(Manager.this, Shop.class);
i.putExtra("Key", prize);
startActivity(i);
Shop.java
Intent myIntent = getIntent();
String receive = myIntent.getStringExtra("Key");
if (getIntent().getExtras() != null)
{
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText(receive);
}
else
{
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText("value is null"); //this is always the result
//why is it null??
}
答案 0 :(得分:1)
函数getExtras()使用putExtras(b)返回放置在Intent中的Bundle
。像这样:
Intent i = new Intent(Manager.this, Shop.class);
i.putExtras(new Bundle());
startActivity(i);
由于您没有使用putExtras函数,因此getIntent()。getExtras()返回null。你应该这样做:
Intent myIntent = getIntent();
String receive = myIntent.getStringExtra("Key");
if (receive != null)
{
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText(receive);
}
else
{
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText("value is null"); //this is always the result
//why is it null??
}
答案 1 :(得分:1)
试试这个你试图访问你设置的不同键
String value= "Your String";
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), Test.class);
// sending data to new activity
i.putExtra("key", value);
startActivity(i);
在下一个活动中
Intent i = getIntent();
// getting attached intent data
String value= i.getStringExtra("value");
// displaying selected product name
txtProduct.setText(value);
答案 2 :(得分:1)
试试这个:
getIntent().getExtras().getString("KEY");
可能应该这样做。