我在getResources()
方法上获得了nullPoint异常。我正在从另一个班级开始下面的活动:
Intent intent = new Intent(getActivity(), FooActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
并且从调用的activity
开始,我设置了非活动类使用的上下文。
class FooActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
Display display = new Display(...);
display.setContext(this.getApplicationContext());
}
}
使用getResources()
方法的类:
class Display{
private static Context context;
public Display(...){ }
public void doSomething(){
**** NullPoint exception Row ****
Bitmap bitmpa = BitmapFactory.decodeResource(context.getResources(), R.drawable.custom_marker);
}
public void setContext(Context context) {
if (context == null)
this.context = context;
}
}
我的Logcat:
08-24 20:18:46.656: E/AndroidRuntime(10526): FATAL EXCEPTION: main
08-24 20:18:46.656: E/AndroidRuntime(10526): java.lang.NullPointerException
08-24 20:18:46.656: E/AndroidRuntime(10526): at com.graphic.core.Display.doSomething(Display.java:43)
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-24 20:18:46.656: E/AndroidRuntime(10526): at android.os.Handler.dispatchMessage(Handler.java:99)
08-24 20:18:46.656: E/AndroidRuntime(10526): at android.os.Looper.loop(Looper.java:137)
08-24 20:18:46.656: E/AndroidRuntime(10526): at android.app.ActivityThread.main(ActivityThread.java:4895)
08-24 20:18:46.656: E/AndroidRuntime(10526): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 20:18:46.656: E/AndroidRuntime(10526): at java.lang.reflect.Method.invoke(Method.java:511)
08-24 20:18:46.656: E/AndroidRuntime(10526): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
08-24 20:18:46.656: E/AndroidRuntime(10526): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
08-24 20:18:46.656: E/AndroidRuntime(10526): at dalvik.system.NativeStart.main(Native Method)
是未正确设置的上下文,导致nullPoint?
答案 0 :(得分:1)
将上下文的初始化添加到构造函数中,如下所示:
public Display(Context context){
this.context = context;
}