0

I got a custom made calendar that can store and show events. I got this from an example online and they used ArrayList to store the data/events.

HomeCollection.date_collection_arr=new ArrayList<HomeCollection>();

The events are created within “onCreate” every time MainActivity runs:

 HomeCollection.date_collection_arr.add( new HomeCollection("2017-07-08" ,"Diwali","Holiday","this is holiday"));

 HomeCollection.date_collection_arr.add( new HomeCollection("2017-07-09" ,"ABC","Holiday","this is holiday"));

The ”HomeCollection” class looks like this:

class HomeCollection {
    public String date="";
    public String name="";
    public String subject="";
    public String description="";


    public static ArrayList<HomeCollection> date_collection_arr;
    public HomeCollection(String date, String name, String subject, String description){

        this.date=date;
        this.name=name;
        this.subject=subject;
        this.description= description;

    }
}

My question is, instead of creating the event every time the app launches with,

HomeCollection.date_collection_arr.add( new HomeCollection("2017-07-08" ,"Holi","Holiday","this is holiday"));

, is it possible to save and load the ”HomeCollection” objects to a SavedPrefereces or something so that the user could add and remove events within the app? Something like this should be possible but how could I do it? Any ideas? :)

1 Answers1

1

Better to be stored in the database, but you can store it as json item using Gson:

Gson

 fun storeHomeCollection(item: HomeCollection) {
        val gson = Gson()
        val json = gson.toJson(item)
        editor.putString("Key", json)
        editor.apply()
    }

and to get the data back

fun getCollection(): HomeCollection? {
        var item = HomeCollection()
        val gson = Gson()
        val json = pr.getString("Key", "empty")
        if (json !== "empty") {
            item = gson.fromJson(json, HomeCollection::class.java)
        }

        return item
    }
Steve
  • 94
  • 1
  • 5