如何使用不同类型的共享preference数据的android?如何使用、不同类型、数据、preference

2023-09-05 05:22:01 作者:ぢ 自娱自乐自己过゜

使用共享preferences我在活动中的一个保存的数据现在我想利用这些数据在另一个活动怎么办?

Using shared preferences I saved data in one of the activity Now I want to use that data in another activity how to do that?

推荐答案

preFS_NAME是你存储在共享preference的价值。

PREFS_NAME is the value you stored in shared preference.

 public static final String PREFS_NAME = "MyPrefsFile";    

// Restore preferences
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean silent = settings.getBoolean("silentMode", false)

看恢复preferences

编辑:要使用它各阶层中,即二传手吸气method.Perfect使用OOPS.You可以调用任何类,多数民众赞成1行作业值

请一个普通的类名作为ReturningClass。

Make a normal class name as ReturningClass.

public class ReturningClass {

private static String MY_STRING_PREF = "mystringpref";

private static String MY_INT_PREF = "shareduserid";

public static SharedPreferences getPrefs(Context context) {


    return context.getSharedPreferences("UserNameAcrossApplication", context.MODE_PRIVATE);

}

public static String getMyStringPref(Context context) {

    return getPrefs(context).getString(MY_STRING_PREF, "default");
}

public static int getMyIntPref(Context context) {

    return getPrefs(context).getInt(MY_INT_PREF, 0);
}

public static void setMyStringPref(Context context, String value) {
    // perform validation etc..
    getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
}

public static void setMyIntPref(Context context, int value) {
    // perform validation etc..
    getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
}

通过调用设置你的价值

Set your value by calling

  ReturningClass.setMyIntPref(mContext,22);

一旦你将你的共享preference.Then只是调用这个method.Just传递context.from类

Once You have set your sharedPreference.Then just call this method.Just pass the context.from your class

 int usersharedpreference=ReturningClass.getMyIntPref(mContext);