How do I retrieve the data from AsyncTasks doInBackground()?

后端 未结 6 1064
耶瑟儿~
耶瑟儿~ 2020-11-28 08:13

I\'ll keep this one as simple as I can.

I have a method in my control layer that uses a class CallServiceTask that extends AsyncTask. When

6条回答
  •  余生分开走
    2020-11-28 09:02

    as @saad-farooq mentioned you can use interface for that. So you can use the Handler.Callback or define your own:

    public interface ClientIF {
    
        public void onResponseReceived(Object result);
    
    }
    

    then you need to implement it in your CallServiceTask

    public abstract class CallServiceTask extends AsyncTask 
        implements ClientIF
    {
        Activity activity;
    
        CallServiceTask(Activity activity) {
            this.activity = activity;
        }
    
        public abstract void onResponseReceived(Object result); 
    
        protected Object[] doInBackground(Object... params) 
        {
            HttpUriRequest req = (HttpUriRequest) params[0];
            String url = (String) params[1];
            return executeRequest(req, url);
        }
    
        protected onPostExecute(Object result) {
            onResponseReceived(result);
        }
    }
    

    note that the costructor is changed so you can call from every Activity class. Then make the instance of this class in your RestClient

    public class RestClient
    {
    CallServiceTask service = new CallServiceTask() {
        @Override
        public void onResponseReceived(Object result) {
        // TODO Auto-generated method stub
    
        }
    };
    
    }
    

提交回复
热议问题