ListView duplicating data in the android application

2

The listView whenever it loads duplicates the data, this happens if I quit the application without shutting down, shutting down the application works normally

Whenever the code BackTask bt =new BackTask(); bt.execute(); is executed the listView is reloaded and ends up duplicating all records.

How can I prevent this from happening?

 public void onStart(){
    super.onStart();
    //execute background task
    BackTask bt =new BackTask();
    bt.execute();
}

//background process to make a request to server and list product information
private class BackTask extends AsyncTask<Void,Void,Void> {

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

        pd = new ProgressDialog(context);
        pd.setTitle("Buscando dados....");
        pd.setMessage("Aguarde!!");
        pd.setCancelable(true);
        pd.setIndeterminate(true);
        pd.show();
    }

    protected Void doInBackground(Void... params) {

        InputStream is = null;
        String result = "";
        try {

            httpclient = new DefaultHttpClient();
            httppost = new HttpPost("http://testebd.com/getproducts.php");
            response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            // Get our response as a String.
            is = entity.getContent();

        } catch (Exception e) {

            if (pd != null)
                pd.dismiss(); //close the dialog if error occurs
            Log.e("ERROR", e.getMessage());
        }

        //convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("ERROR", "Error converting result " + e.toString());
        }
        //parse json data

        try {
            // Remove unexpected characters that might be added to beginning of the string

            result = result.substring(result.indexOf("["));
            JSONArray jArray = new JSONArray(result);

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Product p = new Product();
                p.setpName(json_data.getString("nome"));
                p.setEmail(json_data.getString("email"));
                p.setTel(json_data.getString("telefone"));
                p.setOpc(json_data.getString("opcao"));


                records.add(p);
            }
        } catch (Exception e) {
            Log.e("ERROR", "Error pasting data " + e.toString());
        }
        return null;
    }

    protected void onPostExecute(Void result) {

        if (pd != null) pd.dismiss(); //close dialog
        Log.e("size", records.size() + "");
        adapter.notifyDataSetChanged(); //notify the ListView to get new records

     }


}
    
asked by anonymous 28.10.2015 / 20:29

2 answers

2

There's a problem with Activity Lifecycle .

During its lifetime an Activity passes through different states, in each of them the respective lifecycle callback method is called.

The Task that populates the ListView is called in onStart() .

If you observe the following scheme, which shows the sequence of methods called during the Activity lifecycle, you will see that the onStart() method is called in two different situations: Activity is created and when Activity changes from Stopped status (not visible) to Resumed (visible).

image source

The situation you refer to as "leaving the application without ending" is the situation in which Activity changes from Resumed / strong> for Stopped . When it is made visible again by the transition from Stopped status to Resumed , the onStart() method is again called, causing the items in the list to be duplicated.

The solution proposed by @Thiago uses an artifice to get around the problem. However, it not only forces you to have to delete all items from the list but also to re-call the external service and create the list again.

All "work" can be avoided if Task is called in the onCreate() method.

Pass this code:

//execute background task
BackTask bt =new BackTask();
bt.execute();

into the onCreate() method. So it will only be called once when Activity is created.

    
28.10.2015 / 23:27
1

Try this:

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

        pd = new ProgressDialog(context);
        pd.setTitle("Buscando dados....");
        pd.setMessage("Aguarde!!");
        pd.setCancelable(true);
        pd.setIndeterminate(true);
        pd.show();
       adapter.clear();
    }

adapter.clear();

Before popular the list, you will remove, if there is any record!

    
28.10.2015 / 20:34