Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AsyncTask return multiple values in doInBackground to be used for onPostExecute

Tags:

android

I just read and tested the AsyncTask recently and now I need to know how can I pass multiple values in onPostExecute part. Well I use a JSON parser to get values from web but the values I get from the JSON are multiple values where I pass those values into an array separated by the column headers of each data fetched and this is the part where I supposed to return it for the onPostExecute use. But as far as I know you can only use the return once per run (correct me if I'm wrong please).

Well here's my code so far:

public class GetInfo extends AsyncTask<String, Void, List<String>>{

        private final String TAG = null;
        InputStream is = null;
        StringBuilder sb=null;
        List<String> list = new ArrayList<String>();

        @Override
        protected List<String> doInBackground(String... url) {
            String result = "";

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                //CONNECT TO DATABASE
                 try{
                         HttpClient httpclient = new DefaultHttpClient();
                         HttpPost httppost = new HttpPost(url[0]);
                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                         HttpResponse response = httpclient.execute(httppost);
                         HttpEntity entity = response.getEntity();
                         is = entity.getContent();
                         Log.v(TAG, "connected");
                 }catch(Exception e){
                         Log.v(TAG, "run failed");

                         Log.e("log_tag", "Error in http connection "+e.toString());
                 }

                 //BUFFERED READER FOR INPUT STREAM
                try{
                     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                     sb = new StringBuilder();
                     String line = "0";

                     while ((line = reader.readLine()) != null) {
                             sb.append(line + "\n");
                     }
                     is.close();
                     result=sb.toString();
                     Log.v(TAG, "buffered read");
                 }catch(Exception e){
                     Log.v(TAG, "buffered error");
                         Log.e("log_tag", "Error converting result "+e.toString());
                 }

                //CONVERT JSON TO STRING
                try{
                     Log.v(TAG, result);

                         JSONArray jArray = new JSONArray(result);
                         JSONObject json_data=null;

                         for(int i=0;i<jArray.length();i++){
                             Log.v(TAG, "loop start");

                                 json_data = jArray.getJSONObject(i);
                                 list.add(json_data.getString("id"));
                                 list2.add(json_data.getString("city"));
                                 Log.v(TAG, "list added");
                         }

                 }catch(JSONException e){
                     Log.v(TAG, "rest failed");
                         Log.e("log_tag", "Error parsing data "+e.toString());
                 }

                 Log.v(TAG, list.toString());

                return list; //I also need to return the list2 here

        }

        @Override
        protected void onPostExecute(List<String> result) {
            cities = result; //lost in this part hahaha!
            showCities();
        }

    }

Well to add, this code works fine when I return only one String Array (the list) but I get confused now in the second part. Also cities are declared in the Main class and the ShowCities() only used for display. So I don't bother adding the codes.

like image 534
KaHeL Avatar asked Aug 22 '12 10:08

KaHeL


People also ask

How do I get return value from doInBackground?

You can retreive the return value of protected Boolean doInBackground() by calling the get() method of AsyncTask class : AsyncTaskClassName task = new AsyncTaskClassName(); bool result = task. execute(param1,param2......). get();

How many times an instance of AsyncTask can be executed?

AsyncTask instances can only be used one time.

What method must be overridden for using AsyncTask?

AsyncTask must be subclassed to be used. The subclass will override at least one method ( doInBackground(Params...) ), and most often will override a second one ( onPostExecute(Result) .)

What is the primary reason to use the doInBackground method of an AsyncTask?

doInBackground(Params) − In this method we have to do background operation on background thread. Operations in this method should not touch on any mainthread activities or fragments. onProgressUpdate(Progress…) − While doing background operation, if you want to update some information on UI, we can use this method.


2 Answers

you can Do One thing Make your ArrayList as Static and access it when you want it.

public static List<String> LIST = new ArrayList<String>();
public static List<String> LIST1 = new ArrayList<String>();

public class GetInfo extends AsyncTask<String, Void, List<String>>{

        private final String TAG = null;
        InputStream is = null;
        StringBuilder sb=null;


        @Override
        protected List<String> doInBackground(String... url) {
            String result = "";

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                //CONNECT TO DATABASE
                 try{
                         HttpClient httpclient = new DefaultHttpClient();
                         HttpPost httppost = new HttpPost(url[0]);
                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                         HttpResponse response = httpclient.execute(httppost);
                         HttpEntity entity = response.getEntity();
                         is = entity.getContent();
                         Log.v(TAG, "connected");
                 }catch(Exception e){
                         Log.v(TAG, "run failed");

                         Log.e("log_tag", "Error in http connection "+e.toString());
                 }

                 //BUFFERED READER FOR INPUT STREAM
                try{
                     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                     sb = new StringBuilder();
                     String line = "0";

                     while ((line = reader.readLine()) != null) {
                             sb.append(line + "\n");
                     }
                     is.close();
                     result=sb.toString();
                     Log.v(TAG, "buffered read");
                 }catch(Exception e){
                     Log.v(TAG, "buffered error");
                         Log.e("log_tag", "Error converting result "+e.toString());
                 }

                //CONVERT JSON TO STRING
                try{
                     Log.v(TAG, result);

                         JSONArray jArray = new JSONArray(result);
                         JSONObject json_data=null;

                         for(int i=0;i<jArray.length();i++){
                             Log.v(TAG, "loop start");

                                 json_data = jArray.getJSONObject(i);
                                 LIST.add(json_data.getString("id"));
                                 LIST1.add(json_data.getString("city"));
                                 Log.v(TAG, "list added");
                         }

                 }catch(JSONException e){
                     Log.v(TAG, "rest failed");
                         Log.e("log_tag", "Error parsing data "+e.toString());
                 }

                 Log.v(TAG, list.toString());

                return LIST; //I also need to return the list2 here

        }

        @Override
        protected void onPostExecute(List<String> result) {
            cities = result; //lost in this part hahaha!
            showCities();
        }

    }

now you can use your both LIST & LIST1 when you want it. you also may not need to return arraylist in DoInBackground.

Hope it will Help you.

like image 80
Bhavesh Patadiya Avatar answered Nov 16 '22 03:11

Bhavesh Patadiya


Create a new class with two Lists. Use that class as the return type.

like image 31
Sameer Avatar answered Nov 16 '22 02:11

Sameer