Return value from AsyncTask class onPostExecute method

前端 未结 3 2006
南笙
南笙 2020-11-27 05:50

Ok so now I have Class A that contains some spinners that values will be populated by Class B that extends AsnycTask which grabs the s

相关标签:
3条回答
  • 2020-11-27 06:24

    Problem here is that when you execute your AsynchTask, its doInBackground() methode run in separate thread and the thread that have started this AsynchTask move forward, Thereby changes occur on your variable by AsynchTask does not reflect on parent thread (who stated this AsynchTask) immediately.

    Example --

    class MyAsynchTask
    {
    
    doInbackground()
    {
    a = 2;
    }
    
    }
    
    
    int a = 5;
    
    new MyAsynchTask().execute();
    

    // here a still be 5

    0 讨论(0)
  • 2020-11-27 06:28

    I guess you are trying to read class A variable before it is being set.. Try to do it using callbacks..in the callback function pass the values and refresh your spinners..

    You can create interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute

    For example:

    Your interface:

    public interface OnTaskCompleted{
        void onTaskCompleted(values);
    }
    

    Your Activity:

    public YourActivity implements OnTaskCompleted{
        //your Activity
        YourTask  task = new YourTask(this); // here is the initalization code for your asyncTask
    }
    

    And your AsyncTask:

    public YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
        private OnTaskCompleted listener;
    
        public YourTask(OnTaskCompleted listener){
            this.listener=listener;
        }
    
        //required methods
    
        protected void onPostExecute(Object o){
            //your stuff
            listener.onTaskCompleted(values);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 06:33

    Create a interface like OnCompletRequest() then pass this to your ClassB constructor and simply call the method inside this interface such as complete(yourList list) in the method of onPostExecute(String result)

    0 讨论(0)
提交回复
热议问题