简体   繁体   English

我的侦听器中的Null指针异常

[英]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. 我正在从Fragment类中调用AsyncTask,当我尝试将数据发送回Fragment时,出现空指针异常。

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

My Fragment class implements the interface. 我的Fragment类实现了该接口。

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 https://stackoverflow.com/a/13476196/98514

You have called new twice which created two different AsyncTasks: 您已两次调用new ,从而创建了两个不同的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() . 第一个AsyncTask,您可以在其中设置侦听器,但不要调用execute()
  • the second AsyncTask, which has a null listener but you do call execute() . 第二个AsyncTask,其侦听器为null但您要调用execute()

In the new code, you have one AsyncTask which does both. 在新代码中,您有一个AsyncTask可以同时执行这两个操作。

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. 如果类的成员变量为null,则意味着您永远不会将其初始化为指向构造函数中的非null引用。

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. Java中的所有对象引用类型都将初始化为null,直到将它们指向通过调用new初始化的引用为止。

Where's your constructor? 您的构造函数在哪里?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM