Here is the situation.
i am currently using a list fragment in one of my tabs using action bar. have 3 tabs; tab1, tab2, tab3.. listfragment is on tab2 and just some Fragment on tab1, so when i start my app defualt is ont tab1.. and when i click on tab2 it loads something from the database, TAKE NOTE HAVE ONLY ONE ROW CURRENTLY STORED IN DATABASE so when i click back on tab1 den after clicked again on tab2 suddenly my list has already two items of the same values, it just got duplicated or loaded twice.. and i have only 1 entry on my database.
how do i prevent my fragment to load the list twice, i mean when i load this listfragment the second time around it will just load what is on the db and removes that previous value on listFragment. my theory on this problem is that, the first time i clicked tab2 its ok, when i click tab1 den after tab2, the previous items weren't deleted and when the fragment is loaded it is appended to the previous item..
how do i prevent this from happening..
Here is a sample picture, don't mind the UI flaws but just imagine that entry got doubled from loading the fragment twice.
This is a snippet on onActivityCreated
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadPatientList(0);
}
This is my loadPatientList()
Cursor c = dbHelper.retrieveAllData(PATIENT_TABLE);
c.moveToFirst();
while(!c.isAfterLast())
{
Patients p = new Patients();
Log.d("patient id",Integer.toString(c.getInt(c.getColumnIndex("_id"))));
p.setId(c.getString(c.getColumnIndex("_id")));
p.setFname(c.getString(c.getColumnIndex("firstname")));
p.setMi(c.getString(c.getColumnIndex("middlename")));
p.setLname(c.getString(c.getColumnIndex("lastname")));
p.setAddr(c.getString(c.getColumnIndex("address")));
p.setHosp_name(c.getString(c.getColumnIndex("hosp_name")));
p.setHosp_room(c.getString(c.getColumnIndex("hosp_room")));
p.setAge(c.getInt(c.getColumnIndex("age")));
p.setMed_history(c.getString(c.getColumnIndex("med_history")));
p.setPat_status(c.getInt(c.getColumnIndex("status")));
patient_list.add(p);
c.moveToNext();
}
dbHelper.close();
Collections.sort(patient_list, new Comparator<Patients>() {
public int compare(Patients o1, Patients o2) {
return o1.getLname().compareToIgnoreCase(o2.getLname());
}
});
PatientAdapter patientListAdapter = new PatientAdapter(getActivity(),R.layout.patient_list_item_fragment, patient_list);
setListAdapter(patientListAdapter);
registerForContextMenu(getListView());
onActivityCreated()
is called when you resume the "PatientFragment
". Since List
, allows duplicate, everytime you go back to "PatientFragment
", you fill up patient_list
again and again. Just before enter the while
cycle, try to clear your patient_list
, removing all the elements (List
should be have the clear()
method).