如何使用不同类型的共享preference数据的android? [英] How to use shared preference data in different classes in android?

查看:124
本文介绍了如何使用不同类型的共享preference数据的android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用共享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);

这篇关于如何使用不同类型的共享preference数据的android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆