将类中使用的一组键值对存储在单独的接口中是更好的做法,还是将它存储在strings.xml中更好?

例如:

public interface PreferenceKeys {
    static final String PREF1 = "pref1";
    static final String PREF2 = "pref2";
}

然后在我的代码中以PreferenceKeys.PREF1的形式访问它

在string.xml中存储为名称 - 值对:

<string name="PREF1">pref1</string>
<string name="PREF2">pref2</string>

然后在我的课程中访问它:

String pref1 = getResources().getString(R.string.PREF1);

===============>>#1 票数:3

我想分享我为偏好存储所做的事情,我使用android的内置功能名为SharedPreferences 为了便于访问,我创建了一个名为UserModel SharedPreferences包装器,它包含如下代码:

package tv.gsgw.android.garusuta.model;

import id.flwi.util.ActivityUtil;
import tv.gsgw.android.garusuta.constant.DataConstant;
import android.content.Context;

public class UserModel implements DataConstant {
    Context _context;

    private String authKey = "";
    private String email = "";
    private String password = "";
    private String birthdate = "";
    private String prefacture = "";
    private String bloodType = "";
    private String idealBodyType = "";
    private String duration = "";
    private String stability = "";
    private String skin = "";
    private String relationship = "";
    private String height = "";
    private String weight = "";
    private boolean registerDataChange = false;

    public UserModel(Context context){
        this._context = context;
        loadFromPreferences();
    }

    public void loadFromPreferences(){
        setAuthKey(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_AUTHKEY, ""));
        setEmail(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_EMAIL, ""));
        setPassword(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_PASSWORD, ""));
        setBirthdate(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_BIRTHDATE, ""));
        setPrefacture(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_PREFACTURE, ""));
        setBloodType(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_BLOODTYPE, ""));
        setIdealBodyType(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_BODYTYPE, ""));
        setPeriod(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_DURATIONPERIOD, ""));
        setStability(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_STABILITY, ""));
        setSkin(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_SKINTYPE, ""));
        setRelationship(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_RELATIONSHIP, ""));
        setHeight(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_HEIGHT, ""));
        setWeight(ActivityUtil.getSharedPreferenceString(_context, USER_DATA_FIELD_NAME_WEIGHT, ""));
        setRegisterDataChange(ActivityUtil.getSharedPreferenceBoolean(_context, USER_DATA_FIELD_REGISTER_DATACHANGE, false));
    }

    public void saveIntoPreferences(){
        saveIntoPreferences(true);
    }
    public void saveIntoPreferences(boolean datachanged){
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_AUTHKEY, getAuthKey());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_EMAIL, getEmail());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_PASSWORD, getPassword());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_BIRTHDATE, getBirthdate());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_PREFACTURE, getPrefacture());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_BLOODTYPE, getBloodType());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_BODYTYPE, getIdealBodyType());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_DURATIONPERIOD, getPeriod());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_STABILITY, getStability());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_SKINTYPE, getSkin());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_RELATIONSHIP, getRelationship());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_HEIGHT, getHeight());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_NAME_WEIGHT, getWeight());
        ActivityUtil.setSharedPreference(_context, USER_DATA_FIELD_REGISTER_DATACHANGE, datachanged);
    }

    public String getAuthKey() {
        return authKey;
    }

    public void setAuthKey(String authKey) {
        this.authKey = authKey;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }

    public String getPrefacture() {
        return prefacture;
    }

    public void setPrefacture(String prefacture) {
        this.prefacture = prefacture;
    }

    public String getBloodType() {
        return bloodType;
    }

    public void setBloodType(String bloodType) {
        this.bloodType = bloodType;
    }

    public String getIdealBodyType() {
        return idealBodyType;
    }

    public void setIdealBodyType(String idealBodyType) {
        this.idealBodyType = idealBodyType;
    }

    public String getPeriod() {
        return duration;
    }

    public void setPeriod(String period) {
        this.duration = period;
    }

    public String getSkin() {
        return skin;
    }

    public void setSkin(String skin) {
        this.skin = skin;
    }

    public String getRelationship() {
        return relationship;
    }

    public void setRelationship(String relationship) {
        this.relationship = relationship;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public boolean isRegisterDataChange() {
        return registerDataChange;
    }

    public void setRegisterDataChange(boolean registerDataChange) {
        this.registerDataChange = registerDataChange;
    }

    public String getStability() {
        return stability;
    }

    public void setStability(String stability) {
        this.stability = stability;
    }

    public void setRegistrationChanged(boolean dataChange) {
        this.registerDataChange = dataChange;
    }

    public String toString(){
        String str = "";

        str += "authKey: " + authKey + "\n";
        str += "email: " + email + "\n";
        str += "password: " + password + "\n";
        str += "birthdate: " + birthdate + "\n";
        str += "prefacture: " + prefacture + "\n";
        str += "bloodType: " + bloodType + "\n";
        str += "idealBodyType: " + idealBodyType + "\n";
        str += "duration: " + duration + "\n";
        str += "stability: " + stability + "\n";
        str += "skin: " + skin + "\n";
        str += "relationship: " + relationship + "\n";
        str += "height: " + height + "\n";
        str += "weight: " + weight + "\n";
        str += "registerDataChange: " + (registerDataChange ? "true" : "false") + "\n";

        return str;
    }

}

DataConstant代码中的DataConstant只是一个包含常量变量的类,如下所示:

public static final String USER_DATA_FIELD_NAME_AUTHKEY = "new_AuthKey";
public static final String USER_DATA_FIELD_NAME_EMAIL = "new_Email";
public static final String USER_DATA_FIELD_NAME_PASSWORD = "new_Password";
public static final String USER_DATA_FIELD_NAME_BIRTHDATE = "new_Birthday";
public static final String USER_DATA_FIELD_NAME_PREFACTURE = "new_Prefacture";
public static final String USER_DATA_FIELD_NAME_BLOODTYPE = "new_BloodType";
public static final String USER_DATA_FIELD_NAME_BODYTYPE = "new_IdealBodyType";
public static final String USER_DATA_FIELD_NAME_DURATIONPERIOD = "new_Duration";
public static final String USER_DATA_FIELD_NAME_STABILITY = "new_Stability";
public static final String USER_DATA_FIELD_NAME_SKINTYPE = "new_Skin";
public static final String USER_DATA_FIELD_NAME_RELATIONSHIP = "new_Relationship";
public static final String USER_DATA_FIELD_NAME_HEIGHT = "new_Height";
public static final String USER_DATA_FIELD_NAME_WEIGHT = "new_Weight";
public static final String USER_DATA_FIELD_NAME_PHY_1 = "new_phy1";
public static final String USER_DATA_FIELD_NAME_PHY_2 = "new_phy2";

这使用了一个实用程序类,它还可以帮助您更轻松地使用SharedPreferences

package id.flwi.util;

/**
 * @author Arief Bayu Purwanto
 */
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Calendar;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

public class ActivityUtil {
    public static final String PREFS_NAME = "____MyPrefsFile";

    public static void debugExtra(Bundle extras){
        if( extras != null) {
            Log.i("Log", "printing all extras information");
            java.util.Set<String> keys = extras.keySet();
            java.util.Iterator<String> keyIterator = keys.iterator();
            int index = 0;
            while(keyIterator.hasNext()) {
                Log.i("log", "  extras #" + (++index) + ": " + keyIterator.next());
            }
        } else {
            Log.i("Log", "empty extras");
        }
    }

    public static boolean getSharedPreferenceBoolean(Context c, String preference){
        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        return settings.getBoolean(preference, false);
    }
    public static boolean getSharedPreferenceBoolean(Context c, String preference, boolean defaultValue){
        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        return settings.getBoolean(preference, defaultValue);
    }
    public static String getSharedPreferenceString(Context c, String preference){
        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        return settings.getString(preference, "");
    }
    public static String getSharedPreferenceString(Context c, String preference, String defaultValue){
        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        return settings.getString(preference, defaultValue);
    }
    public static int getSharedPreferenceInt(Context c, String preference, int defaultValue){
        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        return settings.getInt(preference, defaultValue);
    }

    public static long getSharedPreferenceLong(Context c, String preference, long defaultValue){
        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        return settings.getLong(preference, defaultValue);
    }

    public static void setSharedPreference(Context c, String preference, boolean prefValue){

        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(preference, prefValue);
        editor.commit();
    }

    public static void setSharedPreference(Context c, String preference, Long prefValue){

        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(preference, prefValue);
        editor.commit();
    }

    public static void setSharedPreference(Context c, String preference, int prefValue){

        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(preference, prefValue);
        editor.commit();
    }
    public static void setSharedPreference(Context c, String preference, String prefValue){
        SharedPreferences settings = c.getSharedPreferences(ActivityUtil.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(preference, prefValue);
        editor.commit();
    }

}

使用它非常简单:

  1. 要加载数据,您只需调用:

     UserModel sharedData = new UserModel(getApplicationContext()); 
  2. 要更改或检索数据,只需调用它的相关字段getter / setter:

     sharedData.getPassword(); sharedData.setPassword("new password"); 
  3. 最后,如果您更改字段,请不要忘记调用saveIntoPreferences

     sharedData.saveIntoPreferences(); 

希望这有助于解决您的问题。

===============>>#2 票数:0

在我看来,尽量减少项目中“context”的使用,以避免内存泄漏或加载不必要的资源。

共享首选项是一个很好的选择,但需要使用应用程序或活动的上下文。 经常使用,当你想要持久化一些动态值时,就是这种情况吗?

Java接口仅使用最终成员(静态),并且在代码中非常紧凑且易于使用(记住)。 尝试始终使用静态不可变成员(如ip,密码等)。

此外,例如,使用枚举来管理应用程序中的状态或其他内容

public  interface Preferences {
    public String HOST = "http://xxx.xxx.xxx.xxx";
    public String PREF1 = "pref1";
    public String PREF2 = "pref2"; 
    public enum Connection { CONNECTED, DISCONNECTED, UNKNOWN }
}

===============>>#3 票数:0

由你来使用java类或在sharedPreference中,它们之间的区别是你的目的。 在我看来,如果你想要保存常量,只需使用扩展Enum的java类。 否则,用户数据,会话数据保存在sharedPreference中,你可以参考ariefbayu的答案,但在我的建议中使用reflect来获取你的字段的值。

===============>>#4 票数:0

我更喜欢将strings.xml用于需要在布局文件中使用的资源。 对于需要在类中访问的变量,我更喜欢interface方式。

  ask by Bamerza translate from so

未解决问题?本站智能推荐: