繁体   English   中英

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

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

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

用以下替换现有的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() + "]";
    }
}

初始化用户名

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

将对象转换为String

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

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

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

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

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

在这里阅读更多。

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

我们可以通过使用Gson库来实现。 并且可以通过应用程序访问共享首选项。 我已经创建了自己的类来访问共享pref,其中包含所有类型的getter和setter,如String,Int,Object等。

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

您可以使用gson.jar将类对象存储到SharedPreferences中。 您可以在此处https://code.google.com/p/google-gson/downloads/list下载此jar

或者在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);

希望这可以帮助你总结

您只需要替换一行代码即可

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

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

为了获得数据 -

//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,你的defaultValue是“userObject”。 我相信你想要反过来

尝试这个

这将帮助您创建一组共享首选项,并在任何类中的任何位置使用它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM