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

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

在我的应用程序中,我有一个自定义 User class,其中包含一些常规数据(名称等...)。我需要保存该对象并在应用程序的其他页面中随时随地获取它。我用我经常使用的许多方法(当然是静态的)制作了一个助手 class 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();
}

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

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

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

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

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

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

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


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


EDIT2
似乎我没有正确生成对象,因此没有保存任何内容。这是用户 "Singleton" class:

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

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

   User.init(name);

这就是我将对象转换为 String:

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

为了取回数据-

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

希望这对您有所帮助:)

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

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

你有这个方法:

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

但是您发送的是:

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

这意味着您的变量是 this.value 而您的默认值是 "userObject"。我相信你想反过来

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

我通常创建 Preferences class,它公开 getter 和 setter 以快速读取值并将值保存到 SharedPreferences。 我使用 Dagger 作为依赖注入器在代码中的任何地方注入相同的 Preferences 实例。

为什么使用 Singleton 对象而不是 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.

阅读更多here

Preferencesclass的例子:

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

以及如何在 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
        }
    }

你只需要替换一行代码

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

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

将您现有的用户 class 替换为以下

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

初始化用户名

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

将对象转换为字符串

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

我们可以使用 Gson 库来做到这一点。并且可以通过应用程序访问共享偏好。我已经创建了自己的 class 来访问所有类型的 getter 和 setter 的共享 pref,例如 String、Int、Object 等。

使用Gson库,代码如下。如果你想要我创建的class,请告诉我

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

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

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

保存

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

取回

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

希望对你有帮助 求和

试试这个

这将帮助您创建 class 共享偏好并在任何 class 中的任何地方使用它。

  1. 创建一个名为 MySharedPreferences

    的 class
    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");