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

前端 未结 3 1446
夕颜
夕颜 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:29

    OnPostExecute is where you receive the Document when it finishes downloading in the main thread, that is the place where you want to return tour item.

    It occurs to me that you can implement a constructor in the asynctask, something like

    private class RequestTask extends AsyncTask<String, Void, Document> {
    
      private MainClass myClass
    
      public RequestTask(MainClass myClass){
         this.myClass = myClass
      }
    
    ...
    
      protected void onPostExecute(Document doc) {
        super.onPostExecute(doc);
        myClass.myMethod(doc);
      }
    ...
    }
    

    That way you can receive the Document in your main Class

    Hope it helps

    Greetings

    0 讨论(0)
  • 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<Object,Object,Object>{ 
    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.

    0 讨论(0)
  • 2021-01-24 21:52

    You could just call an other function, for example:

        protected void onPostExecute(Document doc) {
            documentIsReady(doc);
        }
    
    }
    
    public void documentIsReady(Document doc)
    {
        //Do somehting
    }
    
    0 讨论(0)
提交回复
热议问题