【发布时间】:2016-09-21 13:04:45
【问题描述】:
我有一个方法由于捕获异常而返回 null 对象。但是,当我尝试检查此对象时,我收到以下错误:
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 可能是个愚蠢的问题,但为什么呢?
-
尝试从Application类中检索上下文,我认为命令是Application.getContext() 不太确定,几个月没用Android Studio
-
查看这里AppContext.getAppContext()
标签: java android exception null