vendredi 18 septembre 2015

How can class.this in a callback can be null?

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...

Thank you for your help!

Artur



from Newest questions tagged java - Stack Overflow http://ift.tt/1UZSGTS
via IFTTT

Aucun commentaire:

Enregistrer un commentaire