简体   繁体   中英

Android: Best way to retain listview content in fragment in tabbed app?

Firstly, this is my first question on StackOverflow so please forgive any formatting issues etc.

I'm writing an Android tablet application which allows users to populate a ListView with content pulled from a web service. At the minute there is one activity which contains a ViewPager which contains 6 fragments on different pages.

The issue is that the data which is downloaded and added to the ListView disappears when the user changes to another tab/back again and the Fragment's OnCreateView method is called (which initialises the ListView back to empty)

What's the best way of keeping the content of the listview besides storing it in a database/sharedprefs. The data in the listview needs to be destroyed when the user logs out/restarts the application, so I'm hoping to not persist it in any way.

the OnCreateView of the ListView container fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_certificate_list, container, false);
    return rootView;
}

And here's the code which populates the ListView when the user hits the download button:

ListView lv = (ListView) callerActivity.findViewById(R.id.listView1);
lv.setAdapter(new CertListAdapter(callerActivity.getBaseContext(), activeCerts));
if (activeCerts.size() > 0) {
       ((TextView) callerActivity.findViewById(R.id.certStatusLabel)).setVisibility(View.GONE);
} else {
        ((TextView) callerActivity.findViewById(R.id.certStatusLabel)).setText(callerActivity.getString(R.string.certsDontExist));
}

the activeCerts variable is an arraylist of certificate objects which are obtained from the web service.

EDIT

Found a solution for this, to simply check if the "activeCerts" variable is null in the onCreateView method and populate the ListView again if it's not null. When the user logs out I'll just set activeCerts to null.

Cheers

"Correct" way:

use Fragment.onSaveInstanceState(Bundle) and Fragment.onActivityCreated(Bundle) to save and restore your items

Cheap way:

set android:configChanges="orientation|keyboardHidden|screenSize" on your activity hosting the fragment

You can also setRetainInstance(true); in the onCreate() of your Fragment

Read more about all this here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM