2015-05-08 48 views
10

我知道getView()可能返回null內onCreateView()方法,但即使我把下面的代碼裏面onActivityCreated()onStart()onViewCreated()方法,它仍然顯示關於一個可能的警告Android Studio中的NullPointerException(儘管我的程序運行時沒有任何問題)。如何擺脫這個警告?NullPointerException異常預警方法

我正在使用片段。

代碼:

datpurchased = (EditText) getView().findViewById(R.id.datepurchased); 
//datpurchased defined as instance variable in the class 

警告:

方法調用 'getView()findViewById(R.id.datepurchased)' 可以 農產品 '顯示java.lang.NullPointerException'

回答

13

Android Studio基於IntelliJ IDEA,這是IntelliJ的一個功能,當您不檢查某個ob時是否會在編譯時給出警告在使用它之前,由方法返回的對象是null。爲了避免這種

一種方法是在始終檢查null或捕捉NullPointerException風格的程序,但它可以得到非常詳細,特別是對的東西,你知道的總是會返回一個對象,永遠不會null

另一種方法是使用註釋如@SuppressWarnings爲使用對象,你知道能不能爲空的方法來抑制這種情況的警告:

@SuppressWarnings({"NullableProblems"}) 
public Object myMethod(Object isNeverNull){ 
    return isNeverNull.classMethod(); 
} 

,或者在你的情況下,線路電平抑制:

//noinspection NullableProblems 
datpurchased = (EditText) getView().findViewById(R.id.datepurchased); //datpurchased defined as instance variable in the class 

儘管如此,確保對象真的不能爲空。

有關IntelliJ's @NotNull和@Nullable註釋的更多信息可以在here找到,更多關於檢查和抑制它們的信息here

+11

我可以用'noinspection ConstantConditions'來抑制我的警告。但關於壓制檢查的鏈接非常有用! – iamreptar

相關問題