make java等到变量变化

时间:2015-06-04 21:09:50

标签: java multithreading sleep

我想让我的代码等到我班级中的任何地方都有变化的最终结果。有没有办法做到这一点?我在Asynctask中执行此操作,我在下面发布。

 public HashMap<String,String> checkbetoutcome() {

    new LoadAllGamet().execute();

    // INSERT CODE HERE

    return finaloutcomes;

}

的AsyncTask

class LoadAllGamet extends AsyncTask<String, String, String> {
        @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());


        }


    }

1 个答案:

答案 0 :(得分:2)

好的,忘记我以前写过的东西。我没有意识到你正在为android编写代码。这是LoadAllGamet的改进版本。这里有两件重要的事情。 1.尽可能在本地定义,即在方法内定义,或者 - 如果不可能 - 在课堂内定义。 2.返回结果,而不是将其放入某个变量中。

class LoadAllGamet extends AsyncTask<String, Void, HashMap<String,String>> {
    protected HashMap<String,String> doInBackground(String ... args) {
        HashMap<String,String> finaloutcomes = new HashMap<>(),
        HashMap<Integer, HashMap<String,String>> allbetsmap = new HashMap<>();

        HttpClient client = new DefaultHttpClient();
        ...
        Log.d("SIZE",Integer.toString(allbetsmap.size()));
        if (allbetsmap.size() == passtocheck.size()) {
          ...
        }
        Log.d("Vital",finaloutcomes.toString());
        return finaloutcomes;
    }
}

每当你想要做一些可能需要一些时间的事情时,你就不应该跑步 在你的应用程序的UI线程中,因为它可以阻止你的UI。 而是异步运行它。一种方法是使用AsyncTask。 让我们假设您想要做某事并且正在处理某些事情 您还希望不时更新UI(例如进度条)。而且一旦你 完成后你想对结果做点什么。 这是写这个的一种方式。

void doSomething() {
  new AsyncTask<String, Progress, Result>() {
    protected Result doInBackground(String... args) {
      //some code
      publishProgress(values);
      //some more code
      return result;
    }

    protected void onProgressUpdate(Progress ... values) {
      updateProgessBars(values);
    }

    protected void onPostExecute(Result result) {
      doSomethingElse(result);
    }
  }.execute();
}

String中的new AsyncTask<String, Progress, Result>是该类型 doInBackground的参数。但是,除非你经常不需要这样做 你想将参数传递给executeProgress是您要发送给onProgressUpdate的值的类型。那 如果您想在后台处理时更新UI,则只需要一个 还在继续。 Result当然是您的结果类型。无论你想要发生什么 doInBackground已完成,您已写入onPostExecute