Android : How to keep the content of a ListView even after changing Fragment through the Drawer

on Thursday, September 25, 2014


I am using Android Studio and I created an Activity that contains a NavigationDrawerFragment. One of the Fragments is loading the content of an SQLite database inside a ListView, using a custom ArrayAdapter with complex items.


My problem is that if I select another fragment in the drawer, then come back to this one, the onCreate() of the Fragment is called again, so is the onCreateView(), and the database is loaded once again.


How can I preserve everything without having to load the database nor populate the list again?


I don't have this problem when orientation changes, so I am a bit confused. Maybe it is because I have a layout for both Portrait and Landscape ?


here is the code of the onCreateView()



public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

getActivity().getActionBar().show();
View view = inflater.inflate(R.layout.fragment_papers, container, false);

allItems = new ArrayList<ItemData>();

getAllItemsFromDB("");


mAdapter = new ItemsList(getActivity(), allItems, this, mDBApi);

// Set the adapter

mListView = (AbsListView) view.findViewById(R.id.list);

mListView.setAdapter(mAdapter);


// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
mListView.setOnScrollListener(this);

return view;
}


and the getAllItemsFromDB() contains something like



public void getAllItemsFromDB(String query){

Cursor c = sqldb.rawQuery("SELECT * FROM 'Table' " + query, null);

while (c.moveToNext()) {

allItems.add(parseSQL(sqldb, c));


}

c.close();

}

0 comments:

Post a Comment