从其他Activity中的AsyncTask返回值

时间:2014-10-03 17:48:06

标签: java android android-asynctask

这是代码,对不起我的英文。

错误是:NullPointerException。一个活动类" menu_fei",一个类Cliente和一个返回值的接口。

public interface AsyncResponse {
    void processFinish(String output);
}

public class Cliente extends AsyncTask<String, String, String> {
    public AsyncResponse delegate = null; // 

    public Cliente(AsyncResponse delegate) {
        this.delegate = delegate;
    }

    public Cliente(String type) {
        this.excute();
    }

    // in method doInBackground return correctly string

    protected void onPostExecute(String result) {
        // Log.d("OutPut",result); // it's ok String!
        if (result == null)
            Log.d("OUTPUT", "NULL"); // for example
        else
            delegate.processFinish(result); // --- ERROR !! --- but result not NUll
    }
}

public class Menu_fei extends Activity implements AsyncResponse {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Cliente asyncTask =new Cliente(this);
        asyncTask.delegate = this;  
        new Cliente("menu_fei");    
    }
}

2 个答案:

答案 0 :(得分:1)

Cliente asyncTask =new Cliente(this);
asyncTask.delegate = this;  
new Cliente("menu_fei");  

您的代码存在的问题是,在第三行中,您正在创建Cliente的新实例而不设置委托。要解决此问题,您只需运行

即可
Cliente asyncTask =new Cliente(this);
asyncTask.execute();

答案 1 :(得分:0)

实现此构造函数

public Cliente(AsyncResponse delegate) {
    this.delegate = delegate;
    this.execute();
}

&#39;类型&#39;在这里没用。

调用

new Cliente(this);

将启动任务