【问题标题】:ASyncTask modifying variable on main threadASyncTask 在主线程上修改变量
【发布时间】:2015-07-05 20:13:09
【问题描述】:

让我先提供一些背景知识。我正在创建一个 Activity,它在创建时将调用 ASyncTask 来检索胆固醇数据列表。这个 ASyncTask 是我的 Activity 中的一个私有类。一切正常,但是,我希望能够在完成后将结果存储回活动中。这样,每次在 Activity 中添加 Cholestoral 数据时,我只需调用一次即可追加数据,而不是重新列出整个内容。

所以,我的问题是:如何设置 onPostExecute 来修改 MainActivity 中的字段? 现在发生的事情是,它通过整个后台任务,正确填充临时列表,返回 Success,然后似乎永远不会进入我将临时列表复制到我的 Main Activity 列表的 onPostExecute()。

我在下面粘贴了源代码,如果有点混乱,我很抱歉。我从以前的活动中重复使用了一些。

public class CholestoralActivity extends ActionBarActivity {
public GraphView graph;
LineGraphSeries<DataPoint> series;
public ArrayList<CholesterolInformation> cholesterolInformationList;

public void setCholesterolInformationList(ArrayList<CholesterolInformation> cholesterolInformationList) {
    this.cholesterolInformationList = cholesterolInformationList;
}

//TODO: Populate ArrayList given JSON response, and call generateDataPoints()
private class ListCholestoralAPI extends AsyncTask<String, Void, String> {
    private ArrayList<CholesterolInformation> tmpcholesterolInformationList;

    @Override
    protected String doInBackground(String... params){
        tmpcholesterolInformationList = new ArrayList<>();
        tmpcholesterolInformationList.clear();
        SharedPreferences sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
        String email = sharedPreferences.getString("email", "");
        String listURL = params[0];
        listURL += email;
        URL url = null;
        String result = null;
        try {
            url = new URL(listURL);
        }
        catch (MalformedURLException e) {
            return e.getMessage();
        }
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
            }
            in.close();
            result = response.toString();
        }
        catch (IOException e) {
            return e.getMessage();
        }
        try {
            JSONObject listObject = new JSONObject(result);
            JSONArray jsonArray = listObject.optJSONArray("cholesterol");
            if (jsonArray != null) {
                for (int i=0; i < jsonArray.length(); i++){
                    JSONObject jsonObject = jsonArray.optJSONObject(i);
                    CholesterolInformation cholesterolInformation = new CholesterolInformation();
                    if (jsonObject != null) {
                        String HDL = jsonObject.getString("hdl");
                        double hdl = Double.parseDouble(HDL);
                        String LDL = jsonObject.getString("ldl");
                        double ldl = Double.parseDouble(LDL);
                        String triGlyceride = jsonObject.getString("triGlycaride");
                        double tri = Double.parseDouble(triGlyceride);
                        String date = jsonObject.getString("date");
                        String unit = jsonObject.getString("unit");
                        cholesterolInformation.setDate(date);
                        cholesterolInformation.setHdl(hdl);
                        cholesterolInformation.setLdl(ldl);
                        cholesterolInformation.setTriGlycaride(tri);
                        cholesterolInformation.setUnit(unit);
                        tmpcholesterolInformationList.add(cholesterolInformation);
                    }
                }

            }
        }
        catch (Exception e){
            return e.getMessage();
        }
        return "Success";
    }

    protected void onPostExecute(String result) {
        if ("Success".equals(result)) {
            System.out.println("Successfully populated list.");
            setCholesterolInformationList(tmpcholesterolInformationList);
        }
    }

【问题讨论】:

  • 你能记录下结果的值并告诉我们你得到了什么吗?
  • 是的,我刚刚在 onPostExecute 中的“if”语句上暂停了调试器,结果包含“Success”,并且临时列表中包含正确的信息。
  • 方法 setCholesterolInformationList 被调用了吗?
  • setCholestoralInformationList 正在被调用,并且没有胆固醇信息列表是 POJO 对象的 ArrayList,稍后将用于在 Graph 上显示数据。
  • 我在想也许我应该在调用onPostExecute() 中的setter 之后立即调用generateDataPoints()initializeGraph() 的方法?

标签: java android multithreading android-asynctask


【解决方案1】:

如果您的 AsyncTask 是 Activity 中的私有类,您可以访问 Activity 类中的变量

所以

 protected void onPostExecute(String result) {
        myTextViewWhichIsInActivity.setText(result);
  }

您是否记录了“结果”尝试

  Log.i(TAG,"result is ["+result+"] is the same as Success");

这样你可以确保你没有任何尾随空格或恶意拼写错误,解析整数总是更好,因为它们比字符串更不容易出错

【讨论】:

    猜你喜欢
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    相关资源
    最近更新 更多