Search code examples
androidsharedpreferencesandroid-sharedpreferences

how to get the data in SharedPreference from another class?


I am trying to get the data stored in shared preference in another 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();
            }

So basically from another class I want to check if MYPREFERENCE has some data and also use that data such that I can further code

I want to do something like this

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

This is on another 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();
            }


    }

     }

Solution

  • From your other class (Activity) you should attach this code in order to take your SharedPreferences:

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

    Also you have not initialized your SharedPreferences instance, you should initialize it like this in your current activity

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

    if you want to check if your SharedPreferences has data you can check the value that the SharedPreference with key value MyUserChoice has , in order not to be equal with blank String. As you see in sharedPref.getString("MyUserChoice",""); the second parameter is the default value when you have not any data. The proper way to check is this if(str != null && !str.isEmpty())