Listview duplicating data in android app

Asked

Viewed 307 times

2

The listview every time it is loaded duplicates the data, this happens if I quit the application without closing, if close 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 stop that 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

     }


}

2 answers

2


The problem has to do with the call Activity Lifecycle.

During his lifetime a Activity passes through different states, in each of them is called the respective life cycle method(Lifecycle callback method).

To Task that fills the Listview is called in the onStart().

The following diagram, which shows the sequence of methods called during the life-cycle of the Activity, verify that the method onStart() is called in two different situations: when the Activity is created and when the Activity state pass Stopped(not visible) to the state Resumed(visible).

inserir a descrição da imagem aqui image source

The situation you refer to as "exit the application without closing" is the one where the Activity raisin d'être Resumed for Stopped.
When it is made visible again, by the transition of the state Stopped for Resumed, the method onStart() is called again, causing the list items to be duplicated.

The solution proposed by @Thiago uses a device to circumvent the problem. However, it not only forces you to have to delete all items from the list but also make a new call to the external service and create the list again.

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

Pass this code:

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

into the method onCreate(). So he will only be called once, when the Activity was created.

1

Try it like 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 populating the list, Voce will remove if there is any record!

  • Show!! It worked great!

  • That’s what you normally call "gambiarra".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.