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

Solution 1:

The only way to do this is using a CallBack. You can do something like this:

new CallServiceTask(this).execute(request, url);

Then in your CallServiceTask add a local class variable and call a method from that class in your onPostExecute:

private class CallServiceTask extends AsyncTask<Object, Void, Object[]>
{
    RestClient caller;

    CallServiceTask(RestClient caller) {
        this.caller = caller;
    }


    protected Object[] doInBackground(Object... params) 
    {
        HttpUriRequest req = (HttpUriRequest) params[0];
        String url = (String) params[1];
        return executeRequest(req, url);
    }

    protected onPostExecute(Object result) {
        caller.onBackgroundTaskCompleted(result);
    }
}

Then simply use the Object as you like in the onBackgroundTaskCompleted() method in your RestClient class.

A more elegant and extendible solution would be to use interfaces. For an example implementation see this library. I've just started it but it has an example of what you want.

Solution 2:

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<Object, Void, Object[]> 
    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

    }
};

}

Solution 3:

You can use get() to retrieve your value/object back from AsyncTask.

new CallServiceTask().execute(parameters).get();

This will return you computed result that you are returning. But this will block your UI till your background process is completed.

Another option is to create an Interface or BroadcastReceiver that you return you the value as soon as your doInBackground() is completed. I had created a demo for the same using Interface and BroadcastReceiver you can check if from my github

Also, by using second approach your UI will not be blocked!

Solution 4:

private void walletStatements() {
        JSONObject post_search = new JSONObject();
        try {

            post_search.put("username", getUserName);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (post_search.length() > 0) {
            try {
               new Getwalletstatements().execute(String.valueOf(post_search));

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    class Getwalletstatements extends AsyncTask<String, String, String> {
        String JsonResponse = null;
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            dialog = new ProgressDialog(ReportsActivity.this);
            dialog.setMessage("Please Wait...");
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            String JsonDATA = params[0];
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            URL url = null;

            try {
                url = new URL(Constant.url+"GetReports_v9.php");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);                // is output buffer writter
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");//set headers and method
                Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
                writer.write(JsonDATA);// json data
                writer.close();

                InputStream inputStream = urlConnection.getInputStream();//input stream
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String inputLine;

                while ((inputLine = reader.readLine()) != null)
                    buffer.append(inputLine + "\n");

                if (buffer.length() == 0) {                    // Stream was empty. No point in parsing.
                    return null;
                }

                JsonResponse = buffer.toString();


                return JsonResponse;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {

                    }
                }
            }


            return null;
        }

        @Override
        protected void onPostExecute(String s) {

            if (JsonResponse != null) {
                try {
                    NetworkIN.iv= Constant.iv;
                    NetworkIN.change=Constant.key;
                    NetworkIN mCrypt=new NetworkIN();
                    String decrypted = new String( mCrypt.decrypt(JsonResponse.trim()) );

                    if(decrypted!=null){
                        JSONObject ordersHistory = new JSONObject(decrypted);
                        msg = ordersHistory.getString("msg");

                        JSONArray jsonArray = ordersHistory.getJSONArray("PPDetails");

                        ordersCount = jsonArray.length();
                        //for (int j = 0; j < jsonArray.length(); j++)
                        for (int j = jsonArray.length() - 1; j >= 0; j--)
                        {
                            JSONObject jsonObject = jsonArray.getJSONObject(j);


                            String message,total_in,inType ;

                            total_in =jsonObject.getString("total_in");
                            inType =jsonObject.getString("in_type");
                            message="Congratulations your wallet is credited by Rs."+total_in+" because of "+inType;
                            ReportsPojo reportsPojo = new ReportsPojo(jsonObject.getString("reg_id"),
                                    jsonObject.getString("username"),
                                    jsonObject.getString("transfer_from"),
                                    jsonObject.getString("transfer_to"),
                                    jsonObject.getString("total_in"),
                                    jsonObject.getString("tds"),
                                    jsonObject.getString("in_amount") ,
                                    jsonObject.getString("out_amount"),
                                    jsonObject.getString("in_type"),
                                    jsonObject.getString("created_on"),
                                    message);

                            reportsItems.add(reportsPojo);
                        }
                    }else{

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (msg.equals("Success")) {

                    reportsAdapter = new ReportsAdapter(ReportsActivity.this, reportsItems);
                    reportsListview.setAdapter(reportsAdapter);

                } else {
                    Toast.makeText(ReportsActivity.this, "Sorry "+msg, Toast.LENGTH_LONG).show();

                }
                dialog.dismiss();
            } else {
                dialog.dismiss();
            }
        }

Solution 5:

public class getOperators extends AsyncTask<Void, Void, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        items = new ArrayList();
        dialog = new ProgressDialog(PrepaidOperatorsListActivity.this);
        dialog.setMessage("Please Wait...");
        dialog.setCancelable(false);
        dialog.show();
    }



    @Override
    protected String doInBackground(Void... params) {
        BufferedReader reader;
        StringBuffer buffer;
        String res = null;

        try {
            URL url = new URL("");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(40000);
            con.setConnectTimeout(40000);
            con.setRequestMethod("GET");
            con.setRequestProperty("Content-Type", "application/json");
            int status = con.getResponseCode();
            InputStream inputStream;
            if (status == HttpURLConnection.HTTP_OK) {
                inputStream = con.getInputStream();
            } else {
                inputStream = con.getErrorStream();
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));
            buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            res = buffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        System.out.println("JSON RESP:" + s);
        String response = s;
        try {

            JSONObject ecomerrce = new JSONObject(response);
            JSONArray jsonArray = ecomerrce.getJSONArray("prepaid_operators");

            for (int j = 0; j < jsonArray.length(); j++) {
                JSONObject jsonObject = jsonArray.getJSONObject(j);

                PrepaidOperatorsPojo prepaidOperatorsPojo = new PrepaidOperatorsPojo(jsonObject.getString("operator_name"), jsonObject.getString("operator_code"), jsonObject.getString("operator_display_comission"), jsonObject.getString("operator_calculate_comission"));
                items.add(prepaidOperatorsPojo);

            }
            if (items.size() > 0) {
                dialog.dismiss();
                prepaidOperatorListAdapter = new PrepaidOperatorListAdapter(PrepaidOperatorsListActivity.this, items);
                rvPrepaidOperatorList.setAdapter(prepaidOperatorListAdapter);

            } else {
                dialog.dismiss();
                Toast.makeText(PrepaidOperatorsListActivity.this, "No Data to display", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}