I have a Fragment. In this Fragment I run a http request on an json-rpc. To handle the result I have something like this in my Callback.
FragmentClass.this.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something
}
});
The problem is, sometimes i get a NullPointerException on the first line... My first intend was, that the fragment got detached to fast maybe because the user selects an other fragment while the request runs and so the
FragmentClass.this.getActivity();
has no activity and returns null. I enclose the whole thing with an if like this:
// New if:
if (FragmentClass.this.getActivity() != null) {
FragmentClass.this.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something
}
});
}
But... Nothing... Now I get an NullPointerException on the if statement. it seems that
FragmentClass.this
is null.
How is that possible. I thought an instance will be hold until no code part needs it and the gc collects it...
Here is the stacktrace that logcat gives me. I have changed the package-name and the classnames. Line 192 is the line of the if statement.
09-18 10:49:36.915 3860-3860/de.unkown.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at de.unkown.app.camera.#FragmentClass$6.onError(FragmentClass.java:192)
at de.unkown.app.webservice.JsonRpcService$10.onError(JsonRpcService.java:497)
at de.unkown.app.webservice.JsonRpcService$DefaultErrorListener.onErrorResponse(JsonRpcService.java:107)
at com.android.volley.Request.deliverError(Request.java:577)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Thank you for your help!
Artur