3

我对android编程很陌生..我有这个问题..我想传递一个值,但结果为null..我想知道为什么会这样..有人可以帮助我吗?提前致谢。我的代码是这样的..

管理器.java

String prize="5";
Intent i = new Intent(Manager.this, Shop.class);
i.putExtra("Key", prize);
startActivity(i);

商店.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??
    }
4

3 回答 3

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);
于 2013-07-19T11:32:06.207 回答
1

函数 getExtras()Bundle使用 putExtras(b) 返回放置在 Intent 中的 a。像这样的东西:

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??
}
于 2013-07-19T11:28:20.300 回答
1

尝试这个:

getIntent().getExtras().getString("KEY");

也许它应该这样做。

于 2013-07-19T12:04:58.870 回答