1

So I'm calling checkbetoutcome() from another activity. My goal is to carry out the AsyncTask and return the finaloutcomes variable which is populated in the onPostExecute() method. How do I achieve this as so that I don't end up with an empty finaloutcomes variable since the AsyncTask is running in the background and the return finaloutcomes, code is executed before the onPostExecute method is complete?

public HashMap<String,String> checkbetoutcome() {
    new LoadAllGamet().execute();
    return finaloutcomes;
}

**Check_Bet.java

public class CheckBet {
    private String bet;
    private ArrayList<Map<String,String>> allbetsmap = new ArrayList<>();
    private ArrayList<String> userstatuses = new ArrayList<>();
    private String status = "open";
    private static String url_check_bet = "****";
    String resulttest;
    private ArrayList<Map<String,String>> passtocheck = new ArrayList<>();
    private String currentitem;
    private String game;
    private onResultListener lister = new onResultListener() {
        @Override
        public void showResult(HashMap<String, String> finaloutcomes) {

        }
    };
    private String c = "";
    JSONArray allgames = null;
    private HashMap<String,String> finaloutcomes = new HashMap<String,String>();


    public CheckBet(String bet, ArrayList<Map<String,String>> passtocheck) {
        this.bet = bet;
        this.passtocheck = passtocheck;

    }


    public HashMap<String,String> checkbetoutcome() {
        new LoadAllGamet(onResultListener lister).execute();
        return finaloutcomes;
    }
    public interface onResultListener {
        void showResult(HashMap<String,String> finaloutcomes);
    }


    class LoadAllGamet extends AsyncTask<String, String, String> {
        onResultListener listener;
        public LoadAllGamet(onResultListener listr) {
            listener = listr;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        protected String doInBackground(String... args) {
           // HttpParams httpParameters = new BasicHttpParams();
           // HttpConnectionParams.setConnectionTimeout(httpParameters, 250000);
            //HttpConnectionParams.setSoTimeout(httpParameters, 250000);
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url_check_bet);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("param", bet));
           // Log.d("CURRENTITEM", currentitem);
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            try {
                HttpResponse response = client.execute(post);
                Log.d("Http Post Responsecxxx:", response.toString());
                HttpEntity httpEntity = response.getEntity();
                InputStream is = httpEntity.getContent();
                JSONObject jObj = null;
                String json = "";
                client.getConnectionManager().closeExpiredConnections();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {

                        if (!line.startsWith("<", 0)) {
                            if (!line.startsWith("(", 0)) {
                                sb.append(line + "\n");
                            }
                        }
                    }

                    is.close();
                    json = sb.toString();

                    json = json.substring(json.indexOf('{'));
                //    Log.d("sbsssssssssss", json);
                    try {
                        jObj = new JSONObject(json);
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    }
                    allgames = jObj.getJSONArray("bets");
                 //   Log.d("WHAT IS MY ARRAY?", allgames.toString());

                       for (Integer i = 0; i < allgames.length(); i++) {
                           HashMap<String,String> statuses = new HashMap<>();
                            JSONObject c = allgames.getJSONObject(i);
                            JSONArray currentbet = c.getJSONArray("bet");
                            Log.d("Single array",currentbet.toString());

                           //  Storing each json item in variable

                           for (Integer a = 0; a < currentbet.length();a++) {
                               JSONObject d = currentbet.getJSONObject(a);
                            String Result = d.getString("Result");
                               String id = d.getString("gid");
                            Log.d("RESULTS",Result);

                           statuses.put(id, Result);
                        }
                           allbetsmap.add(i, statuses);
                           Log.d("ddd", statuses.toString());
                           Log.d("AAA", allbetsmap.get(i).toString());


                       }



                    } catch (Exception e) {
                        Log.e("Buffer Error", "Error converting result " + e.toString());
                    }


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




            return "";
        }



        @Override
        protected void onPostExecute(String param) {
            Log.d("SIZE",Integer.toString(allbetsmap.size()));
            //ArrayList<Map<String,String>> allbetsmap = new ArrayList<>();
            //ArrayList<Map<String,String>> passtocheck = new ArrayList<>();

            if (allbetsmap.size() == passtocheck.size()) {
                for (int i = 0; i < allbetsmap.size();i++) {
                if (allbetsmap.get(i).size() == passtocheck.get(i).size()) {
                    String finaloutcome = "won";
                    for (String a : allbetsmap.get(i).keySet()) {
                        String f = allbetsmap.get(i).get(a);
                        if(f.equals("null")) {
                            finaloutcome = "open";
                        }
                        else if (! (f.equals(passtocheck.get(i).get(a)))) {
                            finaloutcome = "lost";
                            break;
                        }
                    }
                    finaloutcomes.put(Integer.toString(i),finaloutcome);
                }
            }
        }
            Log.d("Vital",finaloutcomes.toString());
            listener.showResult(finaloutcomes);

        }

    }

        // CHANGE THIS AT THE END
    }

**

Alk
  • 5,215
  • 8
  • 47
  • 116

2 Answers2

1

As you already know that AysncTask runs asynchronously and hence new LoadAllGamet().execute(); will return immediately, as a result finaloutcomes would have last value whatever you had stored in it.

For such cases where you want to update your caller(of an AsyncTask) component, say, an Activity, you should use listeners.

See post here to see how can you define and use listeners, basically, an interface defined in your AsyncTask, whose method is implemented by your caller component(such as an Activity) with proper arguments (values you obtained in onPostExecute and to be passed to Activity).

Hope this helps!

Community
  • 1
  • 1
Mithun
  • 2,075
  • 3
  • 19
  • 26
  • It helps, although I'm still confused as to how I would implement it in this case after reviewing that link. Do I have to change the extends AsyncTask line like they did to the type of the variable I wanna return? – Alk Jun 04 '15 at 19:53
  • You can get more info at http://stackoverflow.com/questions/6053602/what-arguments-are-passed-into-asynctaskarg1-arg2-arg3 about what the 3 `parameters` are for in `AsyncTask` and how to use them, rather than just use `. – Mithun Jun 04 '15 at 19:57
1

Create an interface

public interface onResultListener {
    void showResult(String finalOutcome);
}

Activity implements interface

public MyActivity extends Activity implements onResultListener {
    public void getResult() {
        new LoadAllGamet(this).execute();
    }

    void showResult(String finalOutcome){
        // result from your asynctask  
    }
} 

Call interface method from AsyncTask

 public class LoadAllGamet extends AsyncTask<String, String, String> {
    onResultListener listener;
    public LoadAllGamer(OnResultListenre listr) {
    listener = listr;

    @Override
    protected void onPostExecute(String param) {

        Log.d("SIZE",Integer.toString(allbetsmap.size()));
        //ArrayList<Map<String,String>> allbetsmap = new ArrayList<>();
        //ArrayList<Map<String,String>> passtocheck = new ArrayList<>();

        if (allbetsmap.size() == passtocheck.size()) {
            for (int i = 0; i < allbetsmap.size();i++) {
                if (allbetsmap.get(i).size() == passtocheck.get(i).size()) {
                    String finaloutcome = "won";
                    for (String a : allbetsmap.get(i).keySet()) {
                        String f = allbetsmap.get(i).get(a);
                        if(f.equals("null")) {
                            finaloutcome = "open";
                        }
                        else if (! (f.equals(passtocheck.get(i).get(a)))) {
                            finaloutcome = "lost";
                            break;
                        }
                    }
                    finaloutcomes.put(Integer.toString(i),finaloutcome);
                }
            }
        }
        Log.d("Vital",finaloutcomes.toString());
         lister.showResult(finalOutCome);
    }
}
Mithun
  • 2,075
  • 3
  • 19
  • 26
rahul.ramanujam
  • 5,608
  • 7
  • 34
  • 56
  • Couple questions : `public interface onResultListener() { void showResult(HashMap finaloutcomes); }` I'm getting an "expression expected" error in the declaration and the HashMap line – Alk Jun 04 '15 at 19:58
  • Also, here, 'listener.showResult(finaloutcomes); ` "cannot resolve method showResult(HashMap) – Alk Jun 04 '15 at 20:00
  • I have updated my answer , remove () from interface definition just public interface onResultListener { – rahul.ramanujam Jun 04 '15 at 20:00
  • I uploaded the whole java class, can you please have a quick look at what I did wrong, I tried implementing your answer but I'm getting a bunch of errors – Alk Jun 04 '15 at 20:12
  • you have to implement the interface in the activity and pass it in the constructor of the asyntask – rahul.ramanujam Jun 04 '15 at 20:14
  • you mean the activity which calls this java class? – Alk Jun 04 '15 at 20:15