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

发布于 2024-10-26 14:39:25 字数 121 浏览 1 评论 0原文

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

如果可以的话该怎么做呢?如果不可能,还有哪些其他可能性?

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

In Android can we store an object of a class in shared preference and retrieve the object later?

If it is possible how to do it? If it is not possible what are the other possibilities of doing it?

I know that serialization is one option, but I am looking for possibilities using shared preference.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

吾家有女初长成 2024-11-02 14:39:25

是的,我们可以使用 Gson

GitHub

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

用于保存

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

用于获取

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Update1

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

Update2

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

implementation 'com.google.code.gson:gson:2.6.2'

Yes we can do this using Gson

Download Working code from GitHub

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

For save

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

For get

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Update1

The latest version of GSON can be downloaded from github.com/google/gson.

Update2

If you are using Gradle/Android Studio just put following in build.gradle dependencies section -

implementation 'com.google.code.gson:gson:2.6.2'
怀中猫帐中妖 2024-11-02 14:39:25

我们可以使用 Outputstream 将对象输出到内存中。并转换为字符串然后保存在首选项中。例如:

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

当我们需要从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();

we can use Outputstream to output our Object to internal memory. And convert to string then save in preference. For example:

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

when we need to extract Object from Preference. Use the code as below

    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();
悲欢浪云 2024-11-02 14:39:25

不可能。

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

值特别是关于您需要保存的课程吗?

Not possible.

You can only store, simple values in SharedPrefences SharePreferences.Editor

What particularly about the class do you need to save?

爱,才寂寞 2024-11-02 14:39:25

我遇到了同样的问题,这是我的解决方案:

我有类 MyClassArrayList 我想将其保存到共享首选项。首先,我向 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;
}

然后这是保存对象 ArrayList的方法: 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();

这是检索对象的方法:

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;
}

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

I had the same problem, here's my solution:

I have class MyClass and ArrayList<MyClass> that I want to save to Shared Preferences. At first I've added a method to MyClass that converts it to JSON object:

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;
}

Then here's the method for saving object 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();

And here's the method for retrieving the object:

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;
}

Note that StringSet in Shared Preferences is available since API 11.

与风相奔跑 2024-11-02 14:39:25

使用 Gson 库:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}

存储:

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

检索:

String json = getPrefs().getUserJson();

Using Gson Library:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}

Store:

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

Retrieve:

String json = getPrefs().getUserJson();
冷月断魂刀 2024-11-02 14:39:25

使用这个对象 --> TinyDB--Android-Shared-Preferences-Turbo 非常简单。
你可以用它保存大多数常用的对象,如数组、整数、字符串列表等

Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.
you can save most of the commonly used objects with it like arrays, integer, strings lists etc

二智少女 2024-11-02 14:39:25

您可以使用 Complex Preferences Android - by Felipe Silvestre 库来存储自定义对象。
基本上,它使用GSON机制来存储对象。

将对象保存到首选项中:

User user = new User();
user.setName("Felipe");
user.setAge(22); 
user.setActive(true); 

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(
     this, "mypref", MODE_PRIVATE);
complexPreferences.putObject("user", user);
complexPreferences.commit();

并将其检索回来:

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE);
User user = complexPreferences.getObject("user", User.class);

You can use Complex Preferences Android - by Felipe Silvestre library to store your custom objects.
Basically, it's using GSON mechanism to store objects.

To save object into prefs:

User user = new User();
user.setName("Felipe");
user.setAge(22); 
user.setActive(true); 

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(
     this, "mypref", MODE_PRIVATE);
complexPreferences.putObject("user", user);
complexPreferences.commit();

And to retrieve it back:

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE);
User user = complexPreferences.getObject("user", User.class);
无风消散 2024-11-02 14:39:25

您可以使用 GSON,使用 Gradle Build.gradle :

implementation 'com.google.code.gson:gson:2.8.0'

然后在您的代码中,例如使用 Kotlin 的字符串/布尔值对:

        val nestedData = HashMap<String,Boolean>()
        for (i in 0..29) {
            nestedData.put(i.toString(), true)
        }
        val gson = Gson()
        val jsonFromMap = gson.toJson(nestedData)

添加到 SharedPrefs :

        val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
        sharedPrefEditor.putString("sig_types", jsonFromMap)
        sharedPrefEditor.apply()

现在检索数据:

val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
     Log.i("myvalues", key.toString() + map.get(key).toString())
}

You could use GSON, using Gradle Build.gradle :

implementation 'com.google.code.gson:gson:2.8.0'

Then in your code, for example pairs of string/boolean with Kotlin :

        val nestedData = HashMap<String,Boolean>()
        for (i in 0..29) {
            nestedData.put(i.toString(), true)
        }
        val gson = Gson()
        val jsonFromMap = gson.toJson(nestedData)

Adding to SharedPrefs :

        val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
        sharedPrefEditor.putString("sig_types", jsonFromMap)
        sharedPrefEditor.apply()

Now to retrieve data :

val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
     Log.i("myvalues", key.toString() + map.get(key).toString())
}
甜柠檬 2024-11-02 14:39:25

共同共享偏好 (CURD)
SharedPreference:使用简单的 Kotlin 类以值键对的形式存储数据。

var sp = SharedPreference(this);

存储数据:

为了存储 String、Int 和 Boolean 数据,我们有三个具有相同名称和不同参数的方法(方法重载)。

save("key-name1","string value")
save("key-name2",int value)
save("key-name3",boolean)

检索数据:
要检索 SharedPreferences 中存储的数据,请使用以下方法。

sp.getValueString("user_name")
sp.getValueInt("user_id")
sp.getValueBoolean("user_session",true)

清除所有数据:
要清除整个 SharedPreferences,请使用以下代码。

 sp.clearSharedPreference()

删除特定数据:

sp.removeValue("user_name")

公共共享偏好类

import android.content.Context
import android.content.SharedPreferences

class SharedPreference(private val context: Context) {
    private val PREFS_NAME = "coredata"
    private val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    //********************************************************************************************** save all
    //To Store String data
    fun save(KEY_NAME: String, text: String) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putString(KEY_NAME, text)
        editor.apply()
    }
    //..............................................................................................
    //To Store Int data
    fun save(KEY_NAME: String, value: Int) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putInt(KEY_NAME, value)
        editor.apply()
    }
    //..............................................................................................
    //To Store Boolean data
    fun save(KEY_NAME: String, status: Boolean) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putBoolean(KEY_NAME, status)
        editor.apply()
    }
    //********************************************************************************************** retrieve selected
    //To Retrieve String
    fun getValueString(KEY_NAME: String): String? {

        return sharedPref.getString(KEY_NAME, "")
    }
    //..............................................................................................
    //To Retrieve Int
    fun getValueInt(KEY_NAME: String): Int {

        return sharedPref.getInt(KEY_NAME, 0)
    }
    //..............................................................................................
    // To Retrieve Boolean
    fun getValueBoolean(KEY_NAME: String, defaultValue: Boolean): Boolean {

        return sharedPref.getBoolean(KEY_NAME, defaultValue)
    }
    //********************************************************************************************** delete all
    // To clear all data
    fun clearSharedPreference() {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.clear()
        editor.apply()
    }
    //********************************************************************************************** delete selected
    // To remove a specific data
    fun removeValue(KEY_NAME: String) {
        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.remove(KEY_NAME)
        editor.apply()
    }
}

博客:
https://androidkeynotes.blogspot.com/2020/02/shared-preference。 html

Common shared preference (CURD)
SharedPreference: to Store data in the form of value-key pairs with a simple Kotlin class.

var sp = SharedPreference(this);

Storing Data:

To store String, Int and Boolean data we have three methods with the same name and different parameters (Method overloading).

save("key-name1","string value")
save("key-name2",int value)
save("key-name3",boolean)

Retrieve Data:
To Retrieve the data stored in SharedPreferences use the following methods.

sp.getValueString("user_name")
sp.getValueInt("user_id")
sp.getValueBoolean("user_session",true)

Clear All Data:
To clear the entire SharedPreferences use the below code.

 sp.clearSharedPreference()

Remove Specific Data:

sp.removeValue("user_name")

Common Shared Preference Class

import android.content.Context
import android.content.SharedPreferences

class SharedPreference(private val context: Context) {
    private val PREFS_NAME = "coredata"
    private val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    //********************************************************************************************** save all
    //To Store String data
    fun save(KEY_NAME: String, text: String) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putString(KEY_NAME, text)
        editor.apply()
    }
    //..............................................................................................
    //To Store Int data
    fun save(KEY_NAME: String, value: Int) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putInt(KEY_NAME, value)
        editor.apply()
    }
    //..............................................................................................
    //To Store Boolean data
    fun save(KEY_NAME: String, status: Boolean) {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.putBoolean(KEY_NAME, status)
        editor.apply()
    }
    //********************************************************************************************** retrieve selected
    //To Retrieve String
    fun getValueString(KEY_NAME: String): String? {

        return sharedPref.getString(KEY_NAME, "")
    }
    //..............................................................................................
    //To Retrieve Int
    fun getValueInt(KEY_NAME: String): Int {

        return sharedPref.getInt(KEY_NAME, 0)
    }
    //..............................................................................................
    // To Retrieve Boolean
    fun getValueBoolean(KEY_NAME: String, defaultValue: Boolean): Boolean {

        return sharedPref.getBoolean(KEY_NAME, defaultValue)
    }
    //********************************************************************************************** delete all
    // To clear all data
    fun clearSharedPreference() {

        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.clear()
        editor.apply()
    }
    //********************************************************************************************** delete selected
    // To remove a specific data
    fun removeValue(KEY_NAME: String) {
        val editor: SharedPreferences.Editor = sharedPref.edit()
        editor.remove(KEY_NAME)
        editor.apply()
    }
}

Blog:
https://androidkeynotes.blogspot.com/2020/02/shared-preference.html

陈甜 2024-11-02 14:39:25
 1. Create Public class 

public class Prefs {

    //Single Instance object
    private static Prefs instance = null;

    private SharedPreferences sharedPreference = null;


    //Single Instance get
    public static Prefs getPrefInstance() {
        if (instance == null)
            instance = new Prefs();
        return instance;
    }

    @SuppressWarnings("static-access")
    private void openPrefs(Context context) {
        sharedPreference = context.getSharedPreferences(Const.PREFS_FILENAME,
                context.MODE_PRIVATE);
    }

    public void setValue(Context context, String key, String value) {
        openPrefs(context);
        SharedPreferences.Editor prefsEdit = sharedPreference.edit();
        prefsEdit.putString(key, value);
        prefsEdit.commit();
        prefsEdit = null;
        sharedPreference = null;
    }

    public String getValue(Context context, String key, String value) {
        openPrefs(context);
        String result = sharedPreference.getString(key, value);
        sharedPreference = null;
        return result;
    }

    public void remove(Context context, String key) {
        openPrefs(context);
        SharedPreferences.Editor prefsEditor = sharedPreference.edit();
        prefsEditor.remove(key).commit();
        prefsEditor = null;
        sharedPreference = null;
    }
}

 2. If you want to store value in SharedPreferences with below line.
 Prefs.getPrefInstance().setValue(MainActivity.this, Const.GCM_ID, token);

3. If you want to get the value from SharedPreferences.
Prefs.getPrefInstance().getValue(context, Const.GCM_ID, "");

4. If you want to remove the value from SharedPreferences.
Prefs.getPrefInstance().remove(context, Const.GCM_ID);
 1. Create Public class 

public class Prefs {

    //Single Instance object
    private static Prefs instance = null;

    private SharedPreferences sharedPreference = null;


    //Single Instance get
    public static Prefs getPrefInstance() {
        if (instance == null)
            instance = new Prefs();
        return instance;
    }

    @SuppressWarnings("static-access")
    private void openPrefs(Context context) {
        sharedPreference = context.getSharedPreferences(Const.PREFS_FILENAME,
                context.MODE_PRIVATE);
    }

    public void setValue(Context context, String key, String value) {
        openPrefs(context);
        SharedPreferences.Editor prefsEdit = sharedPreference.edit();
        prefsEdit.putString(key, value);
        prefsEdit.commit();
        prefsEdit = null;
        sharedPreference = null;
    }

    public String getValue(Context context, String key, String value) {
        openPrefs(context);
        String result = sharedPreference.getString(key, value);
        sharedPreference = null;
        return result;
    }

    public void remove(Context context, String key) {
        openPrefs(context);
        SharedPreferences.Editor prefsEditor = sharedPreference.edit();
        prefsEditor.remove(key).commit();
        prefsEditor = null;
        sharedPreference = null;
    }
}

 2. If you want to store value in SharedPreferences with below line.
 Prefs.getPrefInstance().setValue(MainActivity.this, Const.GCM_ID, token);

3. If you want to get the value from SharedPreferences.
Prefs.getPrefInstance().getValue(context, Const.GCM_ID, "");

4. If you want to remove the value from SharedPreferences.
Prefs.getPrefInstance().remove(context, Const.GCM_ID);
我们的影子 2024-11-02 14:39:25

无法在 SharedPreferences 中存储对象,我所做的是创建一个公共类,放置我需要的所有参数并创建 setter 和 getter,我能够访问我的对象,

There is no way to store objects in SharedPreferences, What i did is to create a public class, put all the parameters i need and create setters and getters, i was able to access my objects,

晨光如昨 2024-11-02 14:39:25

即使应用程序关闭后或仅在其运行期间,您是否需要检索对象?

您可以将其存储到数据库中。
或者简单地创建一个自定义应用程序类。

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter
    ...
}

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:name=".MyApplication">
        <activity ... />
        ...
    </application>
    ...
</manifest>

然后从每项活动中:

((MyApplication) getApplication).getMyObject();

这不是最好的方法,但它有效。

Do you need to retrieve the object even after the application shutting donw or just during it's running ?

You can store it into a database.
Or Simply create a custom Application class.

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter
    ...
}

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:name=".MyApplication">
        <activity ... />
        ...
    </application>
    ...
</manifest>

And then from every activities do :

((MyApplication) getApplication).getMyObject();

Not really the best way but it works.

太阳男子 2024-11-02 14:39:25

是的。您可以使用 Sharedpreference 存储和检索对象

Yes .You can store and retrive the object using Sharedpreference

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文