以共享首选项存储和检索类对象

and*_*Guy 108 android object sharedpreferences

在Android中,我们可以在共享首选项中存储类的对象,并在以后检索该对象吗?

如果有可能怎么办?如果不可能做到这一点的其他可能性是什么?

我知道序列化是一种选择,但我正在寻找使用共享偏好的可能性.

Par*_*han 319

是的,我们可以使用Gson做到这一点

GitHub下载工作代码

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

为了保存

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
Run Code Online (Sandbox Code Playgroud)

为了得到

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
Run Code Online (Sandbox Code Playgroud)

UPDATE1

可以从github.com/google/gson下载最新版本的GSON.

UPDATE2

如果您正在使用Gradle/Android Studio,请将以下内容放入build.gradle依赖项部分 -

implementation 'com.google.code.gson:gson:2.6.2'
Run Code Online (Sandbox Code Playgroud)

  • 如果它也提到它的局限性,这个答案会更好.我们可以和不能以这种方式存储和检索哪种对象?显然它不适用于所有课程. (5认同)
  • `String json = gson.toJson("MyObject");`应该是对象而不是String. (3认同)

Kis*_*ngk 44

我们可以使用Outputstream将Object输出到内部存储器.并转换为字符串然后保存优先.例如:

    mPrefs = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor ed = mPrefs.edit();
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    ObjectOutputStream objectOutput;
    try {
        objectOutput = new ObjectOutputStream(arrayOutputStream);
        objectOutput.writeObject(object);
        byte[] data = arrayOutputStream.toByteArray();
        objectOutput.close();
        arrayOutputStream.close();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
        b64.write(data);
        b64.close();
        out.close();

        ed.putString(key, new String(out.toByteArray()));

        ed.commit();
    } catch (IOException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

当我们需要从Preference中提取Object时.使用以下代码

    byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
    if (bytes.length == 0) {
        return null;
    }
    ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
    Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
    ObjectInputStream in;
    in = new ObjectInputStream(base64InputStream);
    MyObject myObject = (MyObject) in.readObject();
Run Code Online (Sandbox Code Playgroud)


Blu*_*ell 15

不可能.

您只能在SharedPrefences SharePreferences.Editor中存储简单值

你需要保存什么特别的课程?

  • 另一个选项将其保存为json,然后将其映射回来.使用GSON或jackSON非常简单 (26认同)
  • 将其序列化并将其存储在数据库(SQLite)/平面文件中. (5认同)
  • 答案不完整.可能的解决方案是将pojo转换为ByteArrayOutPutStream并在SharedPreferences中保存为String (5认同)
  • 让我让我的时光机回到 2011 年,然后弄清楚 (2认同)

Mic*_*cer 8

我有同样的问题,这是我的解决方案:

我有MyClass和ArrayList <MyClass>类,我想保存到共享首选项.首先,我向MyClass添加了一个方法,将其转换为JSON对象:

public JSONObject getJSONObject() {
    JSONObject obj = new JSONObject();
    try {
        obj.put("id", this.id);
        obj.put("name", this.name);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}
Run Code Online (Sandbox Code Playgroud)

然后这是保存对象"ArrayList <MyClass> items"的方法:

SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
    SharedPreferences.Editor editor = mPrefs.edit();

    Set<String> set= new HashSet<String>();
    for (int i = 0; i < items.size(); i++) {
        set.add(items.get(i).getJSONObject().toString());
    }

    editor.putStringSet("some_name", set);
    editor.commit();
Run Code Online (Sandbox Code Playgroud)

这是检索对象的方法:

public static ArrayList<MyClass> loadFromStorage() {
    SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);

    ArrayList<MyClass> items = new ArrayList<MyClass>();

    Set<String> set = mPrefs.getStringSet("some_name", null);
    if (set != null) {
        for (String s : set) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                Long id = jsonObject.getLong("id"));
                String name = jsonObject.getString("name");
                MyClass myclass = new MyClass(id, name);

                items.add(myclass);

            } catch (JSONException e) {
                e.printStackTrace();
         }
    }
    return items;
}
Run Code Online (Sandbox Code Playgroud)

请注意,自API 11起,共享首选项中的StringSet可用.


Ram*_*mbu 7

使用Gson库:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Run Code Online (Sandbox Code Playgroud)

商店:

Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);
Run Code Online (Sandbox Code Playgroud)

检索:

String json = getPrefs().getUserJson();
Run Code Online (Sandbox Code Playgroud)