Forum Xamarin.Android

Save data when switching fragment

AlessandroAstoneAlessandroAstone ITMember
edited September 2015 in Xamarin.Android

I want my fragment to store some data when it gets replaced, and to restore that data when it gets called again.
So I coded this:

public class ListFragment : Android.Support.V4.App.Fragment
List<Post> postList = new List<Post>();
    public override void OnSaveInstanceState(Bundle outState)
        outState.PutSerializable("posts", (Java.IO.ISerializable)postList);

    public override void OnCreate(Bundle savedInstanceState)
        if (savedInstanceState != null)
            postList = (List<Post>)savedInstanceState.GetSerializable("posts") ?? new List<Post>();

Then my OnCreateView calls a function that checks for postList.Any() to see if there's data to use, or if it has to be generated again.
Problem is it actually founds no data.

Is OnSaveInstanceState not being called? Or can SetSerializable/GetSerializable fail to serialize c# objects?


  • SebastianSeidel.9226SebastianSeidel.9226 DEInsider, University ✭✭✭✭

    Does your class implements Java.IO.ISerializable?
    Why not try this with a string first and see if it works? If you you could serialize your object tree with c#.

  • I found out that savedInstanceState is always null.
    I even tried calling base.OnSaveInstanceState(outState) after the PutSerializable method, to make sure it was saving it, but the bundle in OnCreate is still null.

  • AlessandroAstoneAlessandroAstone ITMember
    edited September 2015

    My bundle is always null because onSaveInstanceState never gets called. So the problem now is: can it be called when i replace the fragment with another one, or do I have to find a workaround?

  • Something's very wrong here. I tried calling OnSaveInstanceState manually in my OnDestroyView like this:
    public override void OnDestroyView()
    Bundle state = new Bundle();
    state.PutString("posts", Newtonsoft.Json.JsonConvert.SerializeObject(postList));

    (I switched to json serialization, since Java.IO.ISerializable was crashing the app)

    OnSaveInstanceState gets called now, but my bundle in OnCreate is still null!

  • gustaveracostagustaveracosta GBMember ✭✭

    Have you tried to use fragment.add instead of fragment.replace. Saw it somewhere and every1 said that this was the solution for them!

Sign In or Register to comment.