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

how to get the data in SharedPreference from another class?

我正在尝试将数据存储在另一个 class、

的共享首选项中
  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();
            }

所以基本上来自另一个 class 我想检查 MYPREFERENCE 是否有一些数据并使用该数据以便我可以进一步编码

我想做这样的事情

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

这是另一个 activity

   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();
            }


    }

     }

在另一个 activity 中,您可以使用以下方法重新获取共享首选项:

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

并在那里检查:

 mSharedPreferences.contains(KEY);

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

第一 activity

    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();
    }

第 2 activity

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, 整数)

来自您的其他 class (Activity) 您应该附上此代码以便获取您的 SharedPreferences:

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

另外你还没有初始化你的 SharedPreferences 实例,你应该在你当前的 activity

中像这样初始化它
SharedPreferences sharedPref;
sharedPref = getSharedPreferences(MYPREFERENCESKEY , Context.MODE_PRIVATE)

如果你想检查你的SharedPreferences是否有数据你可以检查SharedPreference键值MyUserChoice有的值,为了不等于空白String。正如您在 sharedPref.getString("MyUserChoice",""); 中看到的,当您没有任何数据时,第二个参数是默认值。正确的检查方法是这样的 if(str != null && !str.isEmpty())

在大多数应用程序中,我创建 MyApp 扩展 Application class。 我在 MyApp class.

中编写了大部分 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();
    }

因此,您可以轻松地获取或设置每个 Activity 中的数据。 要获取数据,只需调用:

MyApp.getUsername();

要设置数据,请调用:

MyApp.setUsername("Your User Name");

希望这对你有所帮助。