user1304
user1304

Reputation: 245

When displaying database items in ListView, it's being multiplied every time i change my tabs

I have 3 tabs , and in one of my tabs i have a ListView , which is fetching items from a SQLite database .

The problem is when i change to some other tab, and come back to this tab, my ListViewis showing the database items 2 times, and it's multiplying every time i change my tabs.

Here's my code for tab showing ListView:

public class MyActivity extends Fragment
{
   private ListView mListView;
   private DatabaseHandler db;
   List my = new ArrayList();
   MyListAdapter madapter ;

   //.....

   //...
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
   {
       MyItem i;
       LinearLayout mylayout = (LinearLayout) inflater.inflate(R.layout.my_layout, container, false);

       List<MyItem> l = db.getAllMyItem();

       while(!l.isEmpty() )
       {
           i = l.get(0);
           l.remove(0);
           my.add(new MyList(i.getName(),0));
       }

       mListView = (ListView) mylayout.findViewById(R.id.list);
       madapter = new MyListAdapter(getActivity(), my);

       mListView.setAdapter(madapter);
  }

I know it's my while loop which is fetching the results again and again from database , but what could i do to show my results retrieved from database only once, even after changing tabs and coming back to this Fragment tab.

Upvotes: 0

Views: 169

Answers (1)

Caner
Caner

Reputation: 59198

You never empty your list, so add this before the while loop:

my.clear();

Also I would change the loop as follows because you don't need to remove items from the l list.

for (MyItem i : l) {
     my.add(new MyList(i.getName(),0));
}

Upvotes: 1

Related Questions