简体   繁体   中英

Saving data in fragment android

I have been trying to achieve a certain functionality related to contacts.I have a fragment that shows all the contacts in the device.At first when fragment instance created the contacts will be fetched and stored on a arraylist which will then be displayed in a listview. When fetching for first time,it takes about roughly 3-5 seconds to load contacts,so I have a loading view placed.Is there any way to save this list and retain it back so the fetching of contact list is faster second time.I am replacing fragments on button presses..here is my code.

public static void replaceFragment(FragmentManager fm, int container, Fragment fragment) {
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(container, fragment);
    ft.commit();
}

and called in activity's onCreate() .

 Utils.replaceFragment(getSupportFragmentManager(), R.id.container, new Fragment1());

also on every button press in activity I am calling this method..

@Override
public void onClick(View v) {
    Typeface tf;
    switch (v.getId()) {
        case R.id.frag1_btn:
            Utils.replaceFragment(getSupportFragmentManager(), R.id.container, new Fragment1());
            break;

        case R.id.contact_btn:
            Utils.replaceFragment(getSupportFragmentManager(),
                        R.id.container, new ContactFragment());
            break;
    }
}

I have searched about saveToBackStack() method and onsavedInstanceState(Bundle) and onRetainSavedInstance() , but can they be used here in my case? Also to use these is addToBackStack() method needed?..I' m still a novice at this.Any suggestions?

When you replace the Fragment, you are creating a new instance of your Fragment, then fragment previous state never will be restored.

Utils.replaceFragment(getSupportFragmentManager(), R.id.container, new Fragment1());

Maybe you could use 2 containers, one for each fragment, and instead of replace the framents, show and hide them. If you do that you will can get the previous instance of your fragment.

http://developer.android.com/reference/android/app/FragmentManager.html#findFragmentById(int)

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