如何从另一个类获取SharedPreference中的数据?

时间:2016-07-05 14:26:20

标签: android sharedpreferences android-sharedpreferences

我试图将数据存储在另一个类的共享首选项中,

  public class MyActivity_Settings extends ListActivity {


                //Shared Preference
                SharedPreferences mSharedPreferences;
                public static final String MYPREFERENCES = "MyUserChoice";
                public ArrayList<String> selectedItems = new ArrayList<>();

//onCreate
    mSharedPreferences = getSharedPreferences(MYPREFERENCES, Context.MODE_PRIVATE);

         @Override
            public void finish() {

        String selected = "My string"

                SharedPreferences.Editor prefEditor = mSharedPreferences.edit();
                prefEditor.putString(MYPREFERENCES, selected);
                prefEditor.apply();
                super.finish();
            }

所以基本上从另一个类我想检查MYPREFERENCE是否有一些数据并且还使用那些数据以便我可以进一步编码

我想做这样的事情

 if (mSharedPreferences.contains(MYPREFERENCES)) {
            String savedItems = mSharedPreferences.getString(MYPREFERENCES, "");
            selectedItems.addAll(Arrays.asList(savedItems.split(",")));

这是另一项活动

   MyActivity_Settings mMyActivity_settings = new MyActivity_Settings();

 public class MainActivity extends AppCompatActivity{
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

    //Obviously this is not working

    if(mMyActivity_settings.mSharedPreferences.contains(mMyActivity_settings.MYPREFERENCES){

Toast.makeText(this, " From MainACTIVITY WE HAVE DATA",Toast.LENGTH_LONG).show();
            }


    }

     }

3 个答案:

答案 0 :(得分:2)

在大多数应用中,我创建了扩展MyApp类的Application。 我在MyApp类中编写了大部分SharePreference方法。

public static String getUsername() {
        SharedPreferences mAppPreferences = PreferenceManager
                .getDefaultSharedPreferences(context);
        return mAppPreferences.getString("USERNAME", "");
    }

public static void setUsername(String username) {
        SharedPreferences mAppPreferences = PreferenceManager
                .getDefaultSharedPreferences(context);
        Editor mEditor = mAppPreferences.edit();
        mEditor.putString("USERNAME", username);
        mEditor.commit();
    }

因此,您可以轻松地在每个活动中获取或设置数据。 要获取数据,只需致电:

MyApp.getUsername();

要设置数据,请致电:

MyApp.setUsername("Your User Name");

希望,这对你有所帮助。

答案 1 :(得分:1)

在其他活动中,您可以使用以下命令重新启动sharedprefs:

   mSharedPreferences = gettApplicationContext().getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); 

并在那里检查:

 mSharedPreferences.contains(KEY);

编辑:为清晰起见添加完整示例:

第一项活动

    private final static String MYPREFERENCES = "myapppref";//pref file name
    private final static String MY_PREF_KEY = "timesclicked";//a key for the sharedpref map key->value

    public void onCreate(Bundle savedInstanceState){
        [do usual stuff layout and so on...]
        //first argument is the preference filename, if not existing it will be created, you can use a lot of different files if you need to
        SharedPreference mSharedPreferences = getSharedPreferences(MYPREFERENCES, Context.MODE_PRIVATE);
        //store a value to this pref file, in this case a key MY_PREF_KEY is a costant, value is what you want to store
        mSharedPreferences.edit().putString(MY_PREF_KEY, value).apply();
    }

第二项活动

public void checkMyPrefKeyExistance(){
    //get the pref file with the same name as first activity
    SharedPreference mSharedPreferences = getSharedPreferences(MYPREFERENCES, Context.MODE_PRIVATE);
    //check if key exists
    boolean hasKey = mSharedPreferences.contains(KEY);
    //get value for key, or default value, in this case def val is empty string
    mSharedPreferences.getString(MY_PREF_KEY, "");
}

https://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,int)

答案 2 :(得分:0)

从您的其他课程(活动)中,您应附上此代码,以便获取SharedPreferences

SharedPreferences sharedPref; sharedPref = getSharedPreferences(MYPREFERENCESKEY , Context.MODE_PRIVATE); String selected = sharedPref.getString("MyUserChoice","");

此外,您尚未初始化SharedPreferences个实例,您应该在当前活动中将其初始化为

SharedPreferences sharedPref;
sharedPref = getSharedPreferences(MYPREFERENCESKEY , Context.MODE_PRIVATE)

如果您想检查SharedPreferences是否包含数据,可以检查SharedPreference具有键值MyUserChoice的值,以便不等于空白{{1 }}。正如您在String中看到的那样,当您没有任何数据时,第二个参数是默认值。检查的正确方法是这样 sharedPref.getString("MyUserChoice","");