简体   繁体   中英

Return value from AsyncTask in other Activity

Here is the code, sorry for my English.

The error is : NullPointerException . One Activity Class "menu_fei", One class Cliente and One Interface for returned value.

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");    
    }
}
Cliente asyncTask =new Cliente(this);
asyncTask.delegate = this;  
new Cliente("menu_fei");  

the problem with your code is that in the third line you are creating a new instance of the Cliente without setting the delegate. To fix you can simply run

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

Implement this constructor

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

'type' is no use here.

Calling

new Cliente(this);

will launch the task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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