【问题标题】:How to save the ArrayList<Route> in Sharedpreferecnce? [duplicate]如何在 Shared Preference 中保存 ArrayList<Route>? [复制]
【发布时间】:2018-06-20 19:42:19
【问题描述】:

我有地理点的 latlng 列表

  ArrayList<Route> arrayList

我正在保存这个

 SharedPreferences prefeMain = MainActivitybatchGrp1.this.getSharedPreferences("APPLICATION", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefeMain.edit();

    try {
        Log.e("TASK","Success");
        editor.putString("GROUPA", ObjectSerializer.serialize(arrayListLatLong));
    } catch (IOException e) {
        Log.e("TASK","Fail:: "+e);
        e.printStackTrace();
    }
    editor.commit();

但它给出了一个 IOException

java.io.NotSerializableException: com.directions.route.Route

【问题讨论】:

  • 谷歌你的错误人

标签: java android arraylist sharedpreferences


【解决方案1】:

如果一个类没有实现 java.io.Serializable(就像你的情况一样),你可以将它转换为 JSON 并将 JSON 存储在 SharedPreferences 上。

当然,您还需要反序列化来自 SharedPreferences 的 JSON 字符串。

以下是使用流行的 GSON 库进行序列化/反序列化的示例:

import com.google.gson.Gson;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class GsonTest {

    private static class Test1213 {

        public Test1213(String name) {
            this.name = name;
        }

        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    @Test
    void testConversion() throws IOException {
        Gson gson = new Gson();
        Test1213 john_doe1 = new Test1213("John Doe");
        String john_doe = gson.toJson(john_doe1);
        System.out.println(john_doe);
        Test1213 test1213 = gson.fromJson(john_doe, Test1213.class);
        assertThat(john_doe1.getName(), is(test1213.getName()));
    }
}

此测试序列化为 JSON 并返回。

这是序列化的 JSON:

{"name":"John Doe"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多