【问题标题】:Android - save Object to SharedPreferences and get it anywhere in the appAndroid - 将对象保存到 SharedPreferences 并在应用程序的任何位置获取它
【发布时间】:2015-06-07 01:17:07
【问题描述】:

在我的应用程序中,我有一个自定义的 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();
}

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

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”类:

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

【问题讨论】:

  • 使用序列化进行数据存储是个坏主意。使用一些东西来存储数据。以领域为例。

标签: java android sharedpreferences gson


【解决方案1】:

为了取回数据——

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

希望这会有所帮助:)

【讨论】:

    【解决方案2】:
    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);
    }
    

    【讨论】:

    • 什么是GeneralMethods
    【解决方案3】:

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

    你有这个方法:

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

    但是你发送的是这个:

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

    这意味着你的变量是 this.value 而你的 defaultValue 是“userObject”。我相信你想反其道而行之

    【讨论】:

      【解决方案4】:

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

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

      为什么使用 Singleton 对象而不是 public static 助手?

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

      阅读更多here

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

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

      【讨论】:

        【解决方案5】:

        只需要替换一行代码

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

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

        【讨论】:

        • 我尝试了您的建议,但似乎还有其他问题。当我创建一个新用户并保存它时,当我尝试获取用户名时,我得到 NULL。也许我没有正确保存对象?
        • 你从“String stringUser = gson.toJson(newUser);”得到字符串了吗?这一行我检查了你的代码并且工作正常。
        • 显然没有,我只得到{ }。可能没有正确创建对象。我使用 Singleton 作为基础 User 类。我将使用相关数据更新我的问题。
        【解决方案6】:

        用下面的替换你现有的用户类

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

        【讨论】:

        • 谢谢,按预期工作。为什么必须删除“用户”类的私有构造函数?
        • 为什么必须 implements Serializable 才能保存在 GSON 中?
        【解决方案7】:

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

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

        您可以使用 gson.jar 将类对象存储到 SharedPreferences 中。你可以从这里下载这个罐子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);
        

        希望对你有帮助 求和

        【讨论】:

          【解决方案8】:

          试试这个

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

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

          【讨论】:

            猜你喜欢
            • 2017-07-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-20
            • 1970-01-01
            • 2016-06-23
            • 2016-06-15
            相关资源
            最近更新 更多