0

I am trying to do a "ToDoListApp" and my problem is that when I add some tasks to do and then close the app everything is deleted and the app starts anew.

I saw some other similar questions and it seems the solution is OnSaveInstanceState(Bundle outState) but I have a generic list with a class that I made List<MyClass>. My Problem is that when I write outstate.Put… there is no option for my array I can only choose between int, string, charsequence and parcelable. So my question is how can I save the state of my app?

Georgi Yakov
  • 53
  • 3
  • 11

1 Answers1

0

What you are trying to do here is a thing you should be doing using an SQLite mobile database instead, Can be done like so :

  • Download the NuGet package sqlite-net-pcl by Frank A. Krueger

  • Using SQLite, Create a SQLite connection object

    var db = new SQLiteConnection (dbPath);
    
  • After you have established a connection create your table something like this :

     db.CreateTable<MyClass>();
    
  • Then insert the data that you want to insert into to the table something like this:

     db.Insert(_yourClassObject);
    
  • Retrieve Data something like this;

     var stock = db.Get<MyClass>(**yourPrimaryId**); //single object based on condition
     var stockList = db.Table<MyClass>(); //The list of all data in this table.
    

For a better understanding of how it works refer this

Update

If you want to do it using shared preferences the way to do it would be converting it to JSON and then storing it to preferences as a string something like this:

  • Using Newtonsoft JSON package:

    List<MyClass> your_Object;
    your_Object=FooValueAssigned;// Assumed assignment
    string yourString=JsonConvert.SerializeObject(your_Object); //It accepts any object in your case give your list here
    
  • Now Save it in shared preferences like this:

    ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
    ISharedPreferencesEditor editor = prefs.Edit ();
    editor.PutString("your_list", yourString);
    // editor.Commit();    // applies changes synchronously on older APIs
    editor.Apply();        // applies changes asynchronously on newer APIs
    
  • Retrieve from shared preferences something like this:

    ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
    string mString = prefs.GetString ("your_list", <default value>);
    
  • Convert it back to your object type something like this:

    var yourObjectFromPref= JsonConvert.DeserializeObject<List<MyClass>>(mString);
    
FreakyAli
  • 13,349
  • 3
  • 23
  • 63