ASyncTask修改主线程上的变量

时间:2015-07-05 20:13:10

标签: java android multithreading android-asynctask

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

所以,我的问题是:我如何设置onPostExecute来修改MainActivity中的字段? 现在正在发生的事情是,它通过整个后台任务,正确填充临时列表,返回成功,然后似乎永远不会进入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);
        }
    }

1 个答案:

答案 0 :(得分:0)

如果您的AsyncTask是您活动中的私有类,则可以访问Activity类

中的变量

所以

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

您是否已记录'结果'尝试

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

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