Kevin
Kevin

Reputation: 23634

Null Pointer Exception in my Listener

I am making a call to my AsyncTask from my Fragment class, when i try to send the data back to my Fragment, i get a null pointer exception.

public interface AsyncListner { 
    public void onLoadComplete(List<DocumentResponse> documents);   
}

My Fragment class implements the interface.

public class FragmentClass extends SherlockFragment implements AsyncListner {@
    Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new AsyncTask(Obj, getSherlockActivity()).setListener(this);
        new AsyncTask(Obj, getSherlockActivity()).execute();
    }

    @Override
    public void onLoadComplete(List < Response> data) {
        Log.d("Result", data.toString());
    }
}

I followed this answer. https://stackoverflow.com/a/13476196/98514

Upvotes: 0

Views: 461

Answers (2)

Sam
Sam

Reputation: 86948

You have called new twice which created two different AsyncTasks:

new DocumentsAsyncTask(documentsObject, getSherlockActivity()).setListener(this);
new DocumentsAsyncTask(documentsObject, getSherlockActivity()).execute();

You should only create one:

DocumentsAsyncTask task = new DocumentsAsyncTask(documentsObject, getSherlockActivity());
task.setListener(this);
task.execute();

Notice the difference?
In your existing code you create:

  • the first AsyncTask, where you set the listener but don't call execute().
  • the second AsyncTask, which has a null listener but you do call execute().

In the new code, you have one AsyncTask which does both.

Upvotes: 6

duffymo
duffymo

Reputation: 308753

If a member variable for a class is null, it means you never initialized it to point to a non-null reference in a constructor.

All object reference types in Java are initialized to null until you point them to a reference that you've initialized with a call to new.

Where's your constructor?

Upvotes: 3

Related Questions