![](/img/trans.png)
[英]findViewById() may produce NullPointerException for getView() in HomeFragment.java
[英]findViewById() may produce NullPointerException
我有很多這樣的電話:
(ListView) getView().findViewById(R.id.main_list_view);
(TextView) getView().findViewById(R.id.items_no);
....
和AndroidStudio告訴我他們可能會產生一個NullPointerException
:
方法調用
getView().findViewById(R.id.main_list_view)
可能會產生java.lang.NullPointerException
less ...(Ctrl + F1)此檢查分析方法控制和數據流,以報告始終為真或假的可能條件,靜態證明其值為常量的表達式,以及可能導致可違反合同違約的情況。
標記為
@Nullable
或@NotNull
變量,方法參數和返回值被視為可空(或分別為非空),並在分析期間用於檢查可空性合同,例如報告可能的NullPointerException
錯誤。可以使用
@Contract
注釋定義更復雜的合同,例如:
@Contract("_, null -> null")
- 如果第二個參數為null,則方法返回null@Contract("_, null -> null; _, !null -> !null")
- 如果第二個參數為第二個,則返回null參數為null,否則為null
@Contract("true -> fail")
- 一個典型的assertFalse
方法,如果將true傳遞給它,則拋出異常可以將檢查配置為使用自定義
@Nullable
@NotNull
注釋(默認情況下將使用annotations.jar中的注釋)
幸運的是,有作品,但是我可以對這段代碼進行改進嗎?
這是android.support.v7.app.AppCompatActivity中的一個已知問題,它已在v24中修復。
https://code.google.com/p/android/issues/detail?id=203345
android.support.v4.app.FragmentActivity或android.app.Activity不會有任何問題
你應該忽略這個問題;
正如@DanDar3寫的那樣 - > getView()可以返回null並且AndroidStudio突出顯示。
但是如果你真的想讓AndroidStudio感到高興 - 你可以......:
斷言視圖不是null:
View view = getView();
assert view != null;
(ListView) view.findViewById(R.id.main_list_view);
(TextView) view.findViewById(R.id.items_no);
這是因為getView()
可能返回null並注釋為@Nullable
,請查看源代碼及其JavaDoc - CTRL +單擊代碼中的getView()調用。
/**
* Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
* if provided.
*
* @return The fragment's root view, or null if it has no layout.
*/
@Nullable
public View getView() {
return mView;
}
您可以自己包裝代碼並檢查null以使警告消失,或者將光標放在findViewById()調用內的任何位置,等待幾秒鍾以顯示燈泡(或按Alt + Enter)然后選擇一個建議的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.