2013-07-19 46 views
3

我很新的到Android编程..我有这个问题..我想传递一个值,但结果是空..我不知道为什么会这样..谁能帮助我?提前致谢。我的代码是这样的..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

第一次使用这个和检查数据是否来不来。 Toast.makeText(Shop.this,“”+ receive,Toast.LENGTH_LONG).show(); – TheLittleNaruto

+0

@Kumar我试图Toast.makeText ......但价值仍是空 – user2599219

+0

嘿请举杯它只是这一行 字符串低于收到= myIntent.getStringExtra(“重点”); 如果条件没有在里面。 – TheLittleNaruto

回答

1

功能getExtras()返回一个Bundle使用putExtras放置在Intent(B)。就像这样:

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

试试这个您试图访问不同的密钥你已经设置

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); 
+0

我想这一点。但是我的textview没有发生任何事情。我加了烤面包,价值为零。为什么这样? – user2599219

+0

@ user2599219具有u看到这个网址http://www.androidhive.info/2011/10/android-listview-tutorial/ – 2013-07-19 12:34:35

+0

即使我得到了我的问题,从这个URL的解决方案希望u得到ü运气 – 2013-07-19 12:35:51

1

试试这个:

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

可能是吧应该这样做。