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
}
}