数据不存储在sharedPreferences中

时间:2017-04-10 10:39:24

标签: android sharedpreferences

我是Android新手。我正在使用一个单独的类来存储user_name,mobile_number和IMEI号等数据,使用sharedPreference和自定义模型类(User)。

public class UseSharedPreference {
    private final String NAME = "name";
    private final String MOBILE = "mobile";
    private final String IMEI = "imei";
    private final String STATUS = "status";

    private User user;
    private SharedPreferences sp;
    SharedPreferences.Editor editor;
    Context _context;

    public void storeData(Context context) {
        _context = context;
        sp = _context.getSharedPreferences("user_detail",Context.MODE_PRIVATE);
        editor = sp.edit();

        editor.putString(NAME, user.get_name());
        editor.putString(MOBILE, user.get_mobile());
        editor.putBoolean(STATUS, user.is_status());
        editor.putString(IMEI, user.get_imei());
        editor.apply();
        editor.commit();

        Toast.makeText(context, "User Name : " + sp.getString(NAME, "")
                        + "\nMobile : " + sp.getString(MOBILE, "")
                        + "\nIMEI : " + sp.getString(IMEI, "")
                        + "\n status : " + sp.getBoolean(STATUS, false)
                , Toast.LENGTH_SHORT)
                .show();
    }
}

2 个答案:

答案 0 :(得分:0)

使用此类可以保存,删除和从共享首选项中获取数据:

public class SharedPreferenceHelper {
    private static SharedPreferences preferences;
    private static SharedPreferences.Editor editor;

    public static void initialize(Context con) {
        if (null == preferences) {
            preferences = PreferenceManager.getDefaultSharedPreferences(con);
        }
        if (null == editor) {
            editor = preferences.edit();
        }
    }

    public static void save(String key, String value) {
        editor.putString(key, value);
        editor.commit();
    }
    public  static void save(String key, boolean value){
        editor.putBoolean(key, value);
        editor.commit();
    }
    public static void save(String key, Integer value) {
        save(key, String.valueOf(value));
    }

    public static void save(String key, Long value) {
        save(key, String.valueOf(value));
    }

    public static String get(String key) {
        return preferences.getString(key, null);
    }

    public static Boolean contains(String key) {
        return preferences.contains(key);
    }

    public static void removeKey(String key) {
        editor.remove(key);
        editor.commit();
    }

    public  static void setSPBoolean(String key, boolean value){
        editor.putBoolean(key, value);
        editor.commit();
    }
    public static boolean getBoolean(String key, boolean defValue){
        boolean value = preferences.getBoolean(key, defValue);
        return value;
    }
}

活动类:

SharedPreferenceHelper.initialize(getContext());

SharedPreferenceHelper.save(AppConstants.SAVE_USERNAME, userNameEditText.getText().toString().trim());

答案 1 :(得分:0)

在这种情况下,Donot将变量声明为final。 因为我们无法改变最终变量