In my app there is a button (activity1). When user clicks it, I want no sound in the game. I thought I should do this by using sharedpreferences in activity1 in the onClick method of the button:
SharedPreferences.Editor editor = mPrefs.edit(); editor.putString("sound","1"); editor.commit();
The sound and the game starts in another activity (activity2). I need to read the set sharedpreferences there, but I don't know how to do it.
Thanks
Edit
I have left this line out:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Activity1.this);
Based on your help in the Activity2.class I read the preferences like this:
SharedPreferences myPrefs = getSharedPreferences("Activity1", MODE_PRIVATE); //Activity1.class String ifsound = myPrefs.getString("sound",""); if (ifsound.equals("1")) { Toast.makeText(Activity1.this, "1", Toast.LENGTH_LONG).show(); } else { Toast.makeText(Activity1.this, "0", Toast.LENGTH_LONG).show(); }
How to pass data from one activity to another in Android using shared preferences? Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
To retrieve values from shared preferences: SharedPreferences sp = PreferenceManager. getDefaultSharedPreferences(this); String name = sp. getString("Name", ""); // Second parameter is the default value.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
To give an example, SharedPreferences are useful for storing user preferences, where there are just a handful of variables that need storing. SQLite on the other hand would be better for storing data where there is a large set of items, such as song titles in a music library which need to be searched through.
Use the following functions to add shared preferences and to fetch the saved values from all activities.
public static void setDefaults(String key, String value, Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putString(key, value); editor.apply(); // or editor.commit() in case you want to write data instantly } public static String getDefaults(String key, Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); return preferences.getString(key, null); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With