如何保存List <latlng>?

时间:2016-01-03 17:14:11

标签: java android geolocation

您好我正在使用谷歌地图创建一个应用程序,我希望能够保存一个列表,以便以后用户可以使用它。 在网站上搜索了一下后,我发现人们建议使用gson,但我无法让它工作。我愿意使用它,但我无法使用它。这是我的代码:

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();

}

我在savePoints()时没有收到任何错误;但是当我loadPoints(); RetreivedPoints为空。

如果您认为有更好的方法,我会感谢您的评论!

1 个答案:

答案 0 :(得分:0)

您尚未注册任何TypeAdapters / JsonSerializers,因此它不知道如何将LatLng转换为JSON。阅读此StackOverflow Answer以了解如何使用TypeAdapters / JsonSerializers。