我有3個活動,我們將它們稱爲A,B和C.A和B都具有將視圖發送給C的意圖。設計一個C來自不同事物的設計關於C的活動。我從一個傳遞這樣的數據,以C:Android - 在兩個活動之間傳遞數據獲取NullPointerException
Intent intent = new Intent(this, C.class);
intent.putExtra("Action", "A");
startActivity(intent);
用C的onCreate方法
然後,我有這樣的事情:
Bundle extras = getIntent().getExtras();
if (extras.getString("Action").equals("A")) {
//DO SOMETHING
}
然後我從B到CI有
Intent intent = new Intent(this, C.class);
startActivity(intent);
然後我得到NullPointerException,我猜這是因爲我從B到C時未指定字符串「Action」。
現在我可以在這種情況下爲B添加一行,但是,如果有更多的活動或一個大型的項目,這不會是好事,因爲對於每個活動去一個我會需要這個。
我該如何擁有它,所以我不會在沒有添加「動作」刺激活動B的情況下得到此異常?
感謝您的幫助提前。
編輯
如果我有這樣的從A到C
Intent intent = new Intent(this, C.class);
intent.putExtra("Action", "A");
intent.putExtra("Action2", "A");
startActivity(intent);
這從B到C
Intent intent = new Intent(this, C.class);
intent.putExtra("Action", "B");
startActivity(intent);
然後在C中的onCreate失敗去當從B到C:
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.getString("Action").equals("A")) {
//DO SOMETHING
}
else if (extras.getString("Action2").equals("A")) {
//DO Stuuf
}
}
你從B的意圖沒有額外的,所以當你調用extras.getString()你得到一個NPE。在下面的@Remees M Syde中檢查null。 – Luis 2014-12-04 05:35:24