0

Hello I'm making an app using google maps and I want to be able to save a list so that it can be used opened later by the user. After searching a bit on the site I found that people suggest using gson but I wasn't able to get that to work. I'd be willing to use that but I can't get it to work. Here is my code:

private void loadPoints() throws IOException, ClassNotFoundException {
    Reader isReader = new InputStreamReader(new FileInputStream(file));
    List<LatLng> list = Collections.synchronizedList(new ArrayList<LatLng>());
    Type listOfLatLng = new TypeToken<List<LatLng>>() {
    }.getType();
    String s = gson.toJson(list, listOfLatLng);
    List<LatLng> RetreivedPoints = gson.fromJson(s, listOfLatLng);
    isReader.close();
    System.out.println(RetreivedPoints.get(0) );

    if (RetreivedPoints != null) {
        String joined = TextUtils.join(", ", RetreivedPoints);
        tvCoords.setText(joined);
    }
}


private void savePoints(List<LatLng> l) throws IOException {
    gson = new Gson();


    Writer osWriter = new OutputStreamWriter(new FileOutputStream((file)));
    List<LatLng> list = Collections.synchronizedList(new ArrayList<LatLng>());
    list.add(new LatLng(29, 49));
    gson.toJson(list, osWriter);

    Toast.makeText(MapsActivity.this, "Saved data!", Toast.LENGTH_SHORT).show();

}

I don't get any errors when I savePoints(); but when I loadPoints(); RetreivedPoints is empty.

If you think there is a better approach to this I'd appreciate it if you could comment!

Community
  • 1
  • 1
Seabass77
  • 187
  • 5
  • 13

1 Answers1

0

You haven't registered any TypeAdapters/JsonSerializers, so it won't know how to convert a LatLng to JSON. Read this StackOverflow Answer for how to use TypeAdapters/JsonSerializers.

Community
  • 1
  • 1
samczsun
  • 1,014
  • 6
  • 16
  • I'm a bit overwhelmed by post. Could you clarify a few things for me? It looks like that the reason that RetreivedPoints is empty is because I haven't Serialized it? I would have to do this in savePoints() then I would have to deserialize it in loadPoints()? How do I do either of these? – Seabass77 Jan 03 '16 at 17:58
  • I would recommend having a constant Gson object that is referenced globally. That Gson object should be built using the GsonBuilder class, where you can add on TypeAdapters/JsonSerlializers. You need to make a TypeAdapter/JsonSerializer for the LatLng object, and that way it will be serialized properly – samczsun Jan 03 '16 at 18:18
  • You need to extend TypeAdapter or implement JsonSerializer, depending on whichever one you pick. You also need to implement the read method otherwise it'll be pretty pointless as you can't reconstruct the LatLng from JSON. – samczsun Jan 03 '16 at 20:13