How to return an object from the asynctask to the main class in android

前端 未结 3 1486
夕颜
夕颜 2021-01-24 21:29

I want to return the document to my main class but even using a global variable dosen\'t work it\'s because the asynctask didn\'t finish the job I think is there a solution to g

3条回答
  •  醉酒成梦
    2021-01-24 21:31

    Use a Listener Listener for that. Example in 2 minutes.

    Use an Interface like:

    public interface OnTaskCompleted{
        void onTaskCompleted(Document doc);
    }
    

    Extend your Activity with this Interface:

    public YourActivity implements OnTaskCompleted{
       //your Activity
    }
    

    Let the AsyncTask send an information when it's done.

    public YourTask extends AsyncTask{ 
    private OnTaskCompleted listener;
    
    // all your stuff
    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }
    
    protected void onPostExecute(Object o){
        listener.onTaskCompleted(doc);
    }
    }
    

    Now you implement the onTaskCompleted in your activity and handle the Document which has been given by the asynctask.

提交回复
热议问题