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? :)

3
  • SharedPreferences can store only primitive types. You can achieve what you are trying to do with it BUT using SQLite is much better option Commented Jul 13, 2019 at 0:49
  • @YunusKulyyev Not just primitive types; you can also store String values. I agree that this sounds more like a job for a database, though. Commented Jul 13, 2019 at 0:54
  • Use TinyDB class, search it on Google Commented Jul 13, 2019 at 5:30

1 Answer 1

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
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.