简体   繁体   中英

Storing data in the fragment when activity changes

I would like to design a feed-based app with similar design like Facebook, Twitter or Instagram. In the main screen, I have a FeedActivity which holds a ViewPager for holding 3-4 fragments (represented as tabs)

FeedActivity

++ ListOfItemsFragment (there is a ListView holding posts)
++ OtherFragment
++ SomeOtherFragment

I would like to open another activity (or maybe another fragment in ViewPager) when a user touches a post (listed in ListOfItemsFragment). If I open this new activity (PostDetailActivity) and when I return to the FeedActivity, all data is lost in the ListOfItemsFragment because FeedActivity is created again.

Should I create a new Activity for the post detail, or should I add another fragment to FeedActivity independent of ViewPager (I want this fragment to be a popup, not a part of the tabs).

How can I support this behaviour?

Thanks.

Every time you press back the new Activity instance is created. Hense filled data erases. Just type the following lines in manifest file.

 <activity android:name=".MainActivity"
        android:launchMode="singleTop">
 </activity>

Looking at the problem from a different perspective, sqlite is a solution.

Plus, there's an added bonus of storing states even if your app is completely destroyed and has to restart. See this SO thread .

Simply override this method and store that data that you want to display again

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putInt("intTag", intValue);   // Save all the value that you want to retain
    super.onSaveInstanceState(outState, outPersistentState);
}

and in you onCreate check if the savedInstanceState is not null than get the value and update your

if(savedInstanceState != null) {
    int data = savedInstanceState.getInt("intTag");
    // Retrieve all the data you have settled there
}

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