2013-11-01 109 views
-1

我正在使用导致应用程序崩溃的getExtra。Android GetExtra导致应用程序崩溃

在我与按钮点击活动我使用此代码

String test1ID = "test1ID"; 
Intent intenttesting1 = new Intent(getActivity(), MyActivity.class);      
intenttesting1 .putExtra("Test1", test1ID); 
startActivity(intenttesting1); 

,然后在MyActivity我使用下面的代码来获取意图

Bundle extras = getIntent().getExtras(); 
if(extras != null){ 
    if(extras.getString("Test1").equals("test1ID")){ // if an extra has been set 
     Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show(); 
    } 
} 

这完美的作品。

我有另一个按钮,我想用来类似但发送不同的字符串。 但是这样做会导致应用程序崩溃。

String test2ID = "test2ID"; 
Intent intenttesting2 = new Intent(getActivity(), MyActivity.class);      
intenttesting2 .putExtra("Test2", test2ID); 
startActivity(intenttesting2); 

Bundle 2extras= getIntent().getExtras(); 
if(2extras!= null){ 
    if(2extras.getString("Test2").equals("test2ID")){ // if an extra has been set 
     Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show(); 
    } 
} 

我们无法发送2个不同的意图附加到相同的活动?

不知道我在做什么错,因为这两组代码都可以工作,但是一次只能工作一组,或者应用程序崩溃。

在此先感谢。

+0

你有没有从崩溃的堆栈跟踪? – thegrinner

+0

发布logcat详细信息 – d3m0li5h3r

+0

“我们无法向同一活动发送两个不同的意向附加信息吗?”这是什么意思? – Raghunandan

回答

0

使用yoda notation,以防止空指针引用时使用.equals

Bundle 2extras= getIntent().getExtras(); 
if(2extras!= null) { 
    if("test2ID".equals(2extras.getString("Test2"))){ 
     Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show(); 
    } 
} 
0
I think you should be used this for this situation 

String test1ID = "test1ID"; 
Intent intenttesting1 = new Intent(getActivity(), MyActivity.class);      
intenttesting1 .putExtra("Test1", test1ID); 
startActivity(intenttesting1); 

for next activity 
if("test2ID".equals(getIntent().getStringExtra("Test1"))){ 
     Toast.makeText(getApplicationContext(), "Test 1 Worked", Toast.LENGTH_LONG).show(); 
    }