Java Android - 将对象保存到 SharedPreferences 并在应用程序中的任何位置获取它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29406945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:56:58  来源:igfitidea点击:

Android - save Object to SharedPreferences and get it anywhere in the app

javaandroidsharedpreferencesgson

提问by Alex

In my app I have a custom Userclass which holds some regular data (name etc...). I need to save that object and get it anywhere and anytime in other pages of the app. I made a helper class public final class GeneralMethodswith many methods which I use a lot (static, of course).
In order to save the data Im using Gsonlibrary. I made this method:

在我的应用程序中,我有一个自定义User类,其中包含一些常规数据(名称等)。我需要保存该对象并随时随地在应用程序的其他页面中获取它。我public final class GeneralMethods用很多方法制作了一个辅助类,我经常使用这些方法(当然是静态的)。
为了保存数据我使用Gson库。我做了这个方法:

public static void saveData(Context con, String variable, String data)
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    prefs.edit().putString(variable, data).apply();
}

To save an object, I use this method as follows:

为了保存一个对象,我使用这个方法如下:

Gson gson = new Gson();
String stringUser = gson.toJson(newUser);    
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);

To load the data back, I'm using this static method:

为了重新加载数据,我使用了这个静态方法:

public static String getData(Context con, String variable, String defaultValue)
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    String data = prefs.getString(variable, defaultValue);
    return data;
}

I dont really know how to get the data back, this is what I've done so far:

我真的不知道如何取回数据,这是我到目前为止所做的:

Gson gson = new Gson();
String user="";
String value="";
user = GeneralMethods.getData(SplashScreenActivity.this,value,"userObject");

Im struggling with the getDatamethod, how do I parse the data from Stringback to the Usertype?

我正在努力使用该getData方法,如何将数据从String回解析为User类型?


EDIT
I tried the suggestions bellow and I always get NULL. Maybe I dont save the object in the right way?


编辑
我尝试了下面的建议,我总是得到NULL. 也许我没有以正确的方式保存对象?


EDIT2
It seems Im not generating the object correctly and therefore nothing is being saved. This is the user "Singleton" class:


EDIT2
似乎我没有正确生成对象,因此没有保存任何内容。这是用户“单身”类:

public class User implements Serializable {

    private static User userInstance=null; //the only instance of the class
    private static String userName; //userName = the short phone number
    private User(){}

    public static User getInstance(){
        if(userInstance ==null){
            userInstance = new User();
        }
        return userInstance;
    }

    public static User getUserInstance() {
        return userInstance;
    }

    public String getUserName(){
        return this.userName;
    }

    public static void setUserName(String userName) {
        User.userName = userName;
    }

    public static void init(String _userName) {
        User.setUserName(_userName);
    }
}

This is how i setup the object with the relevant data (user name as the constructor parameter):

这就是我使用相关数据(用户名作为构造函数参数)设置对象的方式:

   User.init(name);

This is how i convert the object to a String:

这就是我将对象转换为 a 的方式String

   Gson gson = new Gson();
    String stringUser = gson.toJson(User.getInstance());
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);

采纳答案by Android Team

Replace your existing User class with below

用以下替换您现有的 User 类

public class User implements Serializable
{

    private static User userInstance = null; // the only instance of the class
    private String userName; // userName = the short phone number
    private User(){}
    public static User getInstance()
    {
        if (userInstance == null)
        {
            userInstance = new User();
        }
        return userInstance;
    }

    public String getUserName()
    {
        return userName;
    }

    public void setUserName(String p_userName)
    {
        userName = p_userName;
    }

    @Override
    public String toString()
    {
        return "User [userName=" + getUserName() + "]";
    }
}

Initialize User Name

初始化用户名

User m_user = User.getInstance();
m_user.setUserName(name);

Convert the object to a String

将对象转换为字符串

Gson gson = new Gson();
String stringUser = gson.toJson(m_user);
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);

回答by Ashish Tamrakar

For getting the data back-

为了取回数据-

//Creating a shared preference
SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

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

Hope this helps :)

希望这可以帮助 :)

回答by John

public static String getData(Context con, String variable)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
String data = prefs.getString(variable, null);
return data;
}

Gson gson = new Gson();
String json = GeneralMethods.getData(SplashScreenActivity.this,"userObject");
if(json!=null){
  MyObject obj = gson.fromJson(json, MyObject.class);
}

回答by vonGohren

You are doing it correctly, but i think you have switched the two fields in the getData method.

你做得对,但我认为你已经切换了 getData 方法中的两个字段。

You have this method:

你有这个方法:

public static String getData(Context con, String variable, String defaultValue)
{....}

But you are sending in this:

但是您发送的是:

user = GeneralMethods.getData(SplashScreenActivity.this,value,"userObject");

That means that your variable is this.value and your defaultValue is "userObject". I believe you want to have it the other way around

这意味着您的变量是 this.value 而您的 defaultValue 是“userObject”。我相信你想反过来

回答by klimat

I'd suggest you to use Dependency Injectionpattern.

我建议你使用依赖注入模式。

I usually create Preferencesclass which exposes getters and setters to quickly read and save values to SharedPreferences. I inject the same instance of Preferencesanywhere in the code using Daggeras Dependency Injector.

我通常创建Preferences暴露 getter 和 setter 的类以快速读取和保存值到SharedPreferences. 我Preferences使用Dagger作为依赖注入器在代码中的任何地方注入相同的实例。

Why use Singletonobject over public statichelpers?

为什么在助手上使用单例对象public static

If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.

如果你有一个直接使用的实用函数的辅助类,它会创建一个隐藏的依赖项;您无法控制谁可以使用它,或者在哪里使用它。通过无状态单例实例注入相同的帮助程序类可以让您控制它的使用位置和使用方式,并在需要时替换它/模拟它/等等。

Read more here.

在这里阅读更多。

Example of Preferencesclass:

Preferences类示例:

@Singleton
public class Preferences {

    private SharedPreferences sharedPreferences;
    private final String NOTIFICATIONS_ENABLED = "NOTIFICATIONS_ENABLED";

    @Inject
    public Preferences(Context context) {
        sharedPreferences = context.getSharedPreferences("Preferences", 0);
    }

    public void setNotificationsEnabled(boolean enabled){
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(NOTIFICATIONS_ENABLED, enabled);
        edit.commit();           
    }

    public boolean isNotificationsEnabled(){
        return sharedPreferences.getBoolean(NOTIFICATIONS_ENABLED, true);
    }
}

and how to use it in Activity:

以及如何使用它Activity

public class MainActivity extends Activity {

    @Inject
    NavigationController navigationController;

    @Inject
    Preferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedObjectGraph.getObjectGraph().inject(this);

        if(preferences.isNotificationsEnabled()){
            // do something
        }
    }

回答by Android Team

You need to just replace one line of code

你只需要替换一行代码

user = GeneralMethods.getData(SplashScreenActivity.this,value,"userObject");

To

user = GeneralMethods.getData(SplashScreenActivity.this,"userObject",value);

回答by Summved Jain

We can do this by using Gson library. And shared preference is accessible through out the application. I have created my own class to access shared pref with getter and setter of all type like String, Int, Object etc.

我们可以通过使用 Gson 库来做到这一点。并且在整个应用程序中都可以访问共享首选项。我已经创建了自己的类来使用所有类型(如 String、Int、Object 等)的 getter 和 setter 访问共享首选项。

To use Gson Library, Below is the code. If you want the class that I have created then let me know

要使用 Gson 库,以下是代码。如果您想要我创建的课程,请告诉我

You can use gson.jar to store class objects into SharedPreferences. You can downlaod this jar from here https://code.google.com/p/google-gson/downloads/list

您可以使用 gson.jar 将类对象存储到 SharedPreferences 中。你可以从这里下载这个 jar https://code.google.com/p/google-gson/downloads/list

Or add GSON dependency in Gradle file

或者在 Gradle 文件中添加 GSON 依赖

compile 'com.google.code.gson:gson:2.5'

编译'com.google.code.gson:gson:2.5'

To Save

保存

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

To Retreive

检索

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

Hope this helps you Summved

希望这对您有所帮助

回答by Sunil

Try this

尝试这个

This will help you to create a class of shared preference and use it any where in any class.

这将帮助您创建一个共享偏好的类,并在任何类的任何地方使用它。

  1. Create a class named as MySharedPreferences

    public class MySharedPreferences
    {
     public static final String mySharedPrefrences = "MyPrefs" ;
     public static SharedPreferences sharedPreferences;
     public static SharedPreferences.Editor editor;
      private static MySharedPreferences instance;
    
    public static MySharedPreferences with(Context context) {
    if (instance == null) {
        instance = new MySharedPreferences(context);
    }
    return instance;
    }
    
    public MySharedPreferences(Context context)
    {
    sharedPreferences=context.getSharedPreferences(mySharedPrefrences, Context.MODE_PRIVATE);
    }
    
    public static String  getUserId(String str_userid)
    {
    if (sharedPreferences!= null) {
        return sharedPreferences.getString(str_userid, "");
    }
    return "";
    }
    
    public void saveUserId(String str_userId_key,String str_userId_value)
    {
    editor = sharedPreferences.edit();
    editor.putString(str_userId_key,str_userId_value);
    editor.commit();
    }
    
    public void clearAllData(Context context)
    {
    sharedPreferences = context.getSharedPreferences(mySharedPrefrences, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear().apply();
    }
    }
    
  2. And use this like

    MySharedPreferences yourPrefrence =MySharedPreferences.with(getActivity());yourPrefrence.saveUserId("str_userId_key",et_title.getText().toString().trim());
    String value = yourPrefrence.getUserId("str_userId_key");
    
  1. 创建一个名为 MySharedPreferences 的类

    public class MySharedPreferences
    {
     public static final String mySharedPrefrences = "MyPrefs" ;
     public static SharedPreferences sharedPreferences;
     public static SharedPreferences.Editor editor;
      private static MySharedPreferences instance;
    
    public static MySharedPreferences with(Context context) {
    if (instance == null) {
        instance = new MySharedPreferences(context);
    }
    return instance;
    }
    
    public MySharedPreferences(Context context)
    {
    sharedPreferences=context.getSharedPreferences(mySharedPrefrences, Context.MODE_PRIVATE);
    }
    
    public static String  getUserId(String str_userid)
    {
    if (sharedPreferences!= null) {
        return sharedPreferences.getString(str_userid, "");
    }
    return "";
    }
    
    public void saveUserId(String str_userId_key,String str_userId_value)
    {
    editor = sharedPreferences.edit();
    editor.putString(str_userId_key,str_userId_value);
    editor.commit();
    }
    
    public void clearAllData(Context context)
    {
    sharedPreferences = context.getSharedPreferences(mySharedPrefrences, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear().apply();
    }
    }
    
  2. 并使用这个

    MySharedPreferences yourPrefrence =MySharedPreferences.with(getActivity());yourPrefrence.saveUserId("str_userId_key",et_title.getText().toString().trim());
    String value = yourPrefrence.getUserId("str_userId_key");