SharedPreferences为Singleton类。什么是正确的方法?

时间:2018-02-13 11:53:08

标签: android singleton android-preferences

我开发的应用程序可能经常使用在任何应用程序位置(例如活动或片段)存储/获取一些配对/值数据的能力。我决定用它来单身。我的班级是否以正确的方式编码?

public class StorageManager {

    private static StorageManager instance;
    public static final String PREF_NAME = "app_settings";
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    public static StorageManager getInstance(Context context) {
        if(instance == null)
            instance = new StorageManager(context.getApplicationContext());
        return instance;
    }

    private StorageManager(Context context) {
        preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    public void setUserEmail(String token)
    {
        editor.putString("email", token);
        editor.commit();
    }

    public String getUserEmail()
    {
        return preferences.getString("email", "");
    }
}

2 个答案:

答案 0 :(得分:1)

实现相同的另一种干净方法:)

    public enum AppSharedPref {
    instance;

    SharedPreferences sharedPreferences;

// setter of the property.
    public void setWeatherUpadte(int value) {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext());
        sharedPreferences.edit().putInt("Weather", value).apply();
    }

// getter of the property.
    public int getWeatherUpadte() {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext());
        return sharedPreferences.getInt("Weather", 0);
    }
}

只需访问该物业:

AppSharedPref.instance.getWeatherUpadte();

答案 1 :(得分:0)

简单易用使用SharedPrefrences

的方式
public class User {
SharedPreferences sharedPreferences;

public String getEnroll() {
    enroll=sharedPreferences.getString("userdata","");
    return enroll;
}

public void setEnroll(String enroll) {
    this.enroll = enroll;
    sharedPreferences.edit().putString("userdata",enroll).commit();
}

public void remove(){
    sharedPreferences.edit().clear().commit();
}

String enroll;

Context context;

public User(Context context){
    this.context=context;
    sharedPreferences=context.getSharedPreferences("userinfo",Context.MODE_PRIVATE);
}

}

创建用户类并在您想要保存用户登录会话时调用它

edt_enroll_login=(EditText)findViewById(R.id.edt_roll_login);
user_roll = edt_enroll_login.getText().toString().trim();

User user=new User(LOGIN.this);//pass the context to user class
user.setEnroll(user_roll);//save user session(here by enrollment number) in userinfo.xml file

这里我使用login.java文件来调用用户类

只需创建用户类对象即可检查并删除用户数据(会话) - User user=new User(yourcallingactivity.this);

要检查用户是否已登录,请使用用户类的user.getEnroll()方法,如果用户已登录,则跳转到用户的主页活动

要在注销后删除用户会话,请使用用户类的user.remove()方法。