【问题标题】:Returning value which is obtained in onPostExecute method of AsyncTask在 AsyncTask 的 onPostExecute 方法中获取的返回值
【发布时间】:2015-08-19 14:02:39
【问题描述】:

所以我从另一个activity 拨打checkbetoutcome()。我的目标是执行 AsyncTask 并返回在 onPostExecute() 方法中填充的 finaloutcomes 变量。我如何实现这一点,以便我不会得到一个空的finaloutcomes 变量,因为AsyncTask 在后台运行并且返回finaloutcomes,代码在onPostExecute 方法完成之前执行?

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
    }

**

【问题讨论】:

    标签: android android-asynctask hashmap


    【解决方案1】:

    您已经知道AysncTask 异步运行,因此new LoadAllGamet().execute(); 将立即返回,因此finaloutcomes 将具有您存储在其中的最后一个值。

    对于您想要更新调用者(AsyncTask)组件(例如 Activity)的这种情况,您应该使用侦听器。

    请参阅帖子here,了解如何定义和使用侦听器,基本上是在AsyncTask 中定义的接口,其方法由您的调用者组件(例如Activity)使用适当的参数(值您在onPostExecute 中获得并传递给Activity)。

    希望这会有所帮助!

    【讨论】:

    • 这很有帮助,尽管在查看该链接后,我仍然对如何在这种情况下实施它感到困惑。我是否必须像他们那样将 extends AsyncTask 行更改为我想要返回的变量的类型?
    • 您可以在stackoverflow.com/questions/6053602/… 获得更多信息,了解parametersAsyncTask 中的用途以及如何使用它们,而不仅仅是使用`
    【解决方案2】:

    创建界面

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

    Activity 实现接口

    public MyActivity extends Activity implements onResultListener {
        public void getResult() {
            new LoadAllGamet(this).execute();
        }
    
        void showResult(String finalOutcome){
            // result from your asynctask  
        }
    } 
    

    从 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);
        }
    }
    

    【讨论】:

    • 几个问题:public interface onResultListener() { void showResult(HashMap&lt;String,String&gt; finaloutcomes); } 我在声明和 HashMap 行中遇到“预期表达式”错误
    • 另外,在这里,'listener.showResult(finaloutcomes); ` "无法解析方法 showResult(HashMap)
    • 我已经更新了我的答案,从接口定义中删除 () 只是 public interface onResultListener {
    • 我上传了整个java类,你能快速看看我做错了什么吗,我尝试实现你的答案,但我得到了一堆错误
    • 必须在activity中实现接口,并在asyntask的构造函数中传递
    猜你喜欢
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 2019-02-07
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    相关资源
    最近更新 更多