I'm tryin to use Sharedpreferences to save an arraylist of objects, but toJson and fromJson are causing fatal exceptions

前端 未结 2 1220
时光说笑
时光说笑 2021-01-16 09:01

My object contains a String, long, and int. Object is called Tracker and I have an arrayList of Trackers. When I try to use toJson i get an error. The same with fromJson.

相关标签:
2条回答
  • 2021-01-16 09:21

    It looks like you're trying to convert a list to json as an object instead of a list. You could just create a wrapper class to hold your list and serialize/deserialize that.

    Create a simple class that acts as a wrapper for your List.

    class TrackWrapper {
        List<Tracker> trackList;
    
        public TrackWrapper(List<Tracker> tracks){
            this.trackList = tracks;
        }
    }
    

    Add items to the list

    Tracker trax = new Tracker(description, timeToCount, imageID);
    track.add(trax);
    

    Create an instance of your wrapper class and pass your list in

    TrackWrapper wrapper = new TrackWrapper(trax);
    

    Serialise the wrapper

    Gson gson = new Gson();
    String json = gson.toJson(wrapper);
    
    0 讨论(0)
  • 2021-01-16 09:30

    You can take a look at my SharedPreferences helper

    // Save list object to another SharedPreference
    SharedPreferencesManager.getInstance(AnotherPreferenceName).putValue("guns", guns);
    List<Gun> datas = SharedPreferencesManager.getInstance(AnotherPreferenceName).getValues("guns", Gun[].class); // get list object
    
    0 讨论(0)
提交回复
热议问题