我有一個方法返回一個null
對象作爲捕獲異常的結果。然而,當我試圖檢查這個對象我收到以下錯誤:在Android應用程序中的NullPointerException
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()' on a
null object reference
我的功能如下:
public static DataPoint getDataFromArray() {
try {
return dataPoints[xIndex][yIndex];
}
catch (ArrayIndexOutOfBoundsException e) {
DataPoint dp = null;
return dp;
}
}
在下面的代碼正在檢查返回值:
DataPoint dp = getDataFromArray();
if(dp == null) {
Toast.makeText(AppContext.getAppContext(), "Out of bounds.", Toast.LENGTH_SHORT).show();
finish();
}
如果我無法將null
分配給我的DataPoint
對象,那麼應如何處理此檢查?謝謝!
解決應用程序上下文後,我看到的錯誤:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.myandroid.myapp/com.myandroid.myapp.activities.
DataEntryActivity}:
java.lang.NullPointerException: Attempt to read from field
'short com.myandroid.myapp.Constants$DataPoint.status' on a null object reference
我提供的,所以我不知道爲什麼它沒有首先使用破壞該活動的代碼之後被讀取,這status
場finish()
方法。
你_Context_爲空 – Piyush
@Piyush可能是一個愚蠢的問題,但爲什麼呢? – petehallw
嘗試從Application類中檢索上下文,我認爲該命令是Application.getContext()不完全確定,未使用Android Studio幾個月 – Cruces