Return data from AsyncTask Android

前端 未结 3 703
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 04:09

I tried to refer similar question on SO, but didn\'t got any help.

In my android app, I\'m planning to implement Recent Quote the user has visited i.e. similar to r

3条回答
  •  难免孤独
    2021-01-05 04:57

    Just for future reference, because this post is a little old:

    I have created an Activity class which has an onStart() method and a separate class for the AsyncTask. Based on my test, after the doInbackground() method the result will be sent to the activity first and after that onPostExecute() will run. This is because based off of logcat, I have my first response data (sent by server) first, then this response will show again from the activity and the last the message in onPostExecute() will show.

    Code for the activity:

    @Override
        protected void onStart() {
            super.onStart();
            String str = "***";
            if(isConnectedToInternet()){
                myAsyncTask.execute();
    
                try {
                    if(myAsyncTask.get())
                        str = myAsyncTask.getResponseMsg();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (CancellationException e) {
                    e.printStackTrace();
                }
            }
            Log.i("Data returned by server2:", str);
        }
    

    AsyncTask code:

    public class MyAsyncTask extends AsyncTask {
    
        private URL url;
        private HttpURLConnection conn;
        private String strResponseMsg;
    
        public MyAsyncTask(String url) throws MalformedURLException{
            this.url = new URL(url);
        }
    
    
        @Override
        protected void onPreExecute() {
            Log.i("Inside AsyncTask", "myAsyncTask is abut to start...");
        }
    
        @Override
        protected Boolean doInBackground(Void... params) {
            boolean status = false;
    
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(Manager.ConnTimeout);
                conn.setReadTimeout(Manager.ReadTimeout);
    
                int responseCode = conn.getResponseCode();
                Log.i("Connection oppened", "Response code is:" + responseCode);
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    if (in != null) {
                        StringBuilder strBuilder = new StringBuilder();
                        // Read character by character              
                        int ch = 0;
                        while ((ch = in.read()) != -1)
                            strBuilder.append((char) ch);
    
                        // Showing returned message
                        strResponseMsg = strBuilder.toString(); 
                        Log.i("Data returned by server:", strResponseMsg);
    
                        status = true;
                    }
                    in.close();
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }       
    
            return status;
        }
    
        @Override
        protected void onPostExecute(Boolean result) {
            Log.i("Inside AsyncTask", "myAsyncTask finished its task. Returning data to caller...");
        }
    
        public String getResponseMsg(){
            return strResponseMsg;
        }
    }
    

提交回复
热议问题