[英]How do I tell if Intent extras exist in Android?
我有這個代碼,檢查從我的應用程序中的許多地方調用的活動上的Intent中的額外值:
getIntent().getExtras().getBoolean("isNewItem")
如果未設置isNewItem,我的代碼會崩潰嗎? 在我打電話之前,有沒有辦法判斷它是否已經設定?
處理這個問題的正確方法是什么?
正如其他人所說, getIntent()
和getExtras()
可以返回null。 因此,您不希望將調用鏈接在一起,否則您最終可能會調用null.getBoolean("isNewItem");
這將拋出NullPointerException
並導致您的應用程序崩潰。
以下是我將如何實現這一目標。 我認為它以最好的方式格式化,並且很容易被其他可能正在閱讀您的代碼的人理解。
// You can be pretty confident that the intent will not be null here.
Intent intent = getIntent();
// Get the extras (if there are any)
Bundle extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("isNewItem")) {
boolean isNew = extras.getBoolean("isNewItem", false);
// TODO: Do something with the value of isNew.
}
}
您實際上不需要調用containsKey("isNewItem")
因為如果額外不存在,則getBoolean("isNewItem", false)
將返回false。 你可以將上面的內容壓縮成這樣的東西:
Bundle extras = getIntent().getExtras();
if (extras != null) {
boolean isNew = extras.getBoolean("isNewItem", false);
if (isNew) {
// Do something
} else {
// Do something else
}
}
您還可以使用Intent
方法直接訪問附加內容。 這可能是最干凈的方法:
boolean isNew = getIntent().getBooleanExtra("isNewItem", false);
實際上這里的任何方法都是可以接受的。 選擇一個對你有意義並且那樣做的方法。
你可以這樣做:
Intent intent = getIntent();
if(intent.hasExtra("isNewItem")) {
intent.getExtras().getBoolean("isNewItem");
}
問題不是getBoolean()
而是getIntent().getExtras()
以這種方式測試:
if(getIntent() != null && getIntent().getExtras() != null)
myBoolean = getIntent().getExtras().getBoolean("isNewItem");
順便說一句,如果isNewItem
不存在,則返回de default vaule false
。
問候。
如果沒有Intent
, getIntent()
將返回null
,所以使用...
boolean isNewItem = false;
Intent i = getIntent();
if (i != null)
isNewItem = i.getBooleanExtra("isNewItem", false);
除非你使用它,否則它不會崩潰! 你不必得到它,如果它存在,但如果你嘗試,出於某種原因,使用一個“額外”,它不存在你的系統將崩潰。
所以,嘗試做類似的事情:
final Bundle bundle = getIntent().getExtras();
boolean myBool=false;
if(bundle != null) {
myBool = bundle.getBoolean("isNewItem");
}
這樣您就可以確保您的應用不會崩潰。 (並確保你有一個有效的Intent
:))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.