【问题标题】:Android Duplicate list view due to onResume由于onResume,Android重复列表视图
【发布时间】:2018-11-15 11:05:56
【问题描述】:

您好,我是 android 新手。有一个arrayList 和一个ListView。我使用 AsyncTask 类从 MYSQL DB 调用数据库。此 AsyncTask 类设置 mArrayList(这是 arrayList)。为了在我从另一个活动返回时更新列表视图,我使用了 onResume()。这是部分。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mold_breakage_history);

        brokenMoldListView = findViewById(R.id.brokenMoldListView);

        mArrayList = new ArrayList<>();
        GetData task = new GetData();
        task.execute("http://www.cafe24.com/aaa.php");

    }

    @Override
    protected void onResume() {
        super.onResume();

        mArrayList = new ArrayList<>();
        GetData task = new GetData();
        task.execute("http://www.cafe24.com/aaa.php");

在 onResume() 中,我初始化了 mArrayList 并再次调用 AsyncTask 来更新 ListView。问题是当这个活动第一次执行时,ListView 被复制了。但是,当我从这个活动的下一页返回时,问题就消失了。我希望首次执行活动时不存在此问题。请帮忙。 这是 AsyncTask 类的代码。

@SuppressLint("StaticFieldLeak")
    private class GetData extends AsyncTask<String, Void, String> {
        ProgressDialog progressDialog;
        String errorString = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(MoldBreakageHistoryActivity.this,
                    "Please Wait", null, true, true);
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            progressDialog.dismiss();
            Log.d(TAG, "response  - " + result);

            mJsonString = result;
            showResult();
        }


        @Override
        protected String doInBackground(String... params) {

            String serverURL = params[0];


            try {

                URL url = new URL(serverURL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();


                httpURLConnection.setReadTimeout(5000);
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.connect();


                int responseStatusCode = httpURLConnection.getResponseCode();
                Log.d(TAG, "response code - " + responseStatusCode);

                InputStream inputStream;
                if (responseStatusCode == HttpURLConnection.HTTP_OK) {
                    inputStream = httpURLConnection.getInputStream();
                } else {
                    inputStream = httpURLConnection.getErrorStream();
                }


                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                StringBuilder sb = new StringBuilder();
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }


                bufferedReader.close();


                return sb.toString().trim();


            } catch (Exception e) {

                Log.d(TAG, "InsertData: Error ", e);
                errorString = e.toString();

                return null;
            }

        }
    }


    private void showResult() {
        try {
            JSONObject jsonObject = new JSONObject(mJsonString);
            JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject item = jsonArray.getJSONObject(i);

                String brokenDate = item.getString(TAG_BROKEN_DATE);
                String moldCode = item.getString(TAG_MOLD_CODE);
                String finalHitting = item.getString(TAG_FINAL_HITTING_TIMES);


                HashMap<String, String> hashMap = new HashMap<>();

                hashMap.put(TAG_BROKEN_DATE, brokenDate);
                hashMap.put(TAG_MOLD_CODE, moldCode);
                hashMap.put(TAG_FINAL_HITTING_TIMES, finalHitting);


                mArrayList.add(hashMap);
            }

            ListAdapter adapter = new SimpleAdapter(
                    MoldBreakageHistoryActivity.this, mArrayList, R.layout.list_item_broken_mold,
                    new String[]{TAG_BROKEN_DATE, TAG_MOLD_CODE, TAG_FINAL_HITTING_TIMES},
                    new int[]{R.id.brokenDateListItem, R.id.brokenMoldListItem, R.id.finalHittingTimesListItem}
            );

            brokenMoldListView.setAdapter(adapter);

        } catch (JSONException e) {

            Log.d(TAG, "showResult : ", e);
        }
    }

【问题讨论】:

  • 它是重复的,因为它在代码中也是重复的。您正在调用它两次。通过活动生命周期了解这些方法是如何被调用的。

标签: android listview android-asynctask


【解决方案1】:

删除这个:

 mArrayList = new ArrayList<>();
 GetData task = new GetData();
 task.execute("http://www.cafe24.com/aaa.php");

来自onCreateonResumeonCreate 之后立即执行,并且您的异步任务执行了两次,这就是它首先被复制的原因。当你回击时,只有 onResume 被执行,所以问题就会发生。

【讨论】:

    【解决方案2】:

    请删除

     mArrayList = new ArrayList<>();
     GetData task = new GetData();
     task.execute("http://www.cafe24.com/aaa.php");
    

    来自您的 onCreate 方法。

    但是,如果您需要在 onCreate 中执行 som 场景并在 onResume 中执行其他场景,您可以在仅执行新任务之前使用mArrayList.clear();

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多