Edit and save shared preferences in Android Studio
I can access shared preferences in Android Studio from Device file explorer, but after editing the file, the changed values aren't saved. How can I save the changes?
You're not editing the files directly. When you open a file that's on the device, Android Studio is actually pulling a copy to your local machine.
For example, if I selected this random i_log
file from my SDCard it ends up here on my local machine under Documents
on Mac (shown in the top status bar in Android Studio).
If you want to save the changes back to the device, you need to "upload" the file back to the device.
- On the folder in the device explorer you want to move the file to, right-click.
- Select Upload..
- In the file chooser dialog, navigate to the local copy you edited.
AS will push that file back to the device.
Edit shared preferences from DDMS
First, you should probably make sure your app isn't running before doing this.
You have to use the File Explorer option. Navigate to
data -> com.yourpackage -> shared_pref
Click the xml and at the top right click pull
.
Edit the xml on your computer.
Once you're done, click push
(also top right).
If you pushed the same file to the same device to the same directory, the next time you launch the app, you should see your updated values.
Android: Viewing SharedPreferences file?
I have ran into this issue in the past (not having root permission on the file system but needing access to the applications data folder). If you don't have a rooted device or a developer device such as the ADP1 then you can try running your application on the emulator and then accessing the files from the "File Explorer" in eclipse or DDMS.
EDIT #1:
Try using the getAll function of sharedPreferences and saving that to a file, I will see if I can throw together a sample.
EDIT #2:
Example Code, created from random samples around the net, probably not the best way to do it, but I tested it and it does work. It writes a file to the root of your sdcard. Make sure you have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
set in your manifest
private void saveSharedPreferences()
{
// create some junk data to populate the shared preferences
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefEdit = prefs.edit();
prefEdit.putBoolean("SomeBooleanValue_True", true);
prefEdit.putInt("SomeIntValue_100", 100);
prefEdit.putFloat("SomeFloatValue_1.11", 1.11f);
prefEdit.putString("SomeStringValue_Unicorns", "Unicorns");
prefEdit.commit();
// BEGIN EXAMPLE
File myPath = new File(Environment.getExternalStorageDirectory().toString());
File myFile = new File(myPath, "MySharedPreferences");
try
{
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
Map<String,?> prefsMap = prefs.getAll();
for(Map.Entry<String,?> entry : prefsMap.entrySet())
{
pw.println(entry.getKey() + ": " + entry.getValue().toString());
}
pw.close();
fw.close();
}
catch (Exception e)
{
// what a terrible failure...
Log.wtf(getClass().getName(), e.toString());
}
}
Sources One Two Three
Where are shared preferences stored?
SharedPreferences are stored in an xml file in the app data folder, i.e.
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
or the default preferences at:
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
SharedPreferences added during runtime are not stored in the Eclipse project.
Note: Accessing /data/data/<package_name>
requires superuser privileges
View an Android App's shared preferences?
Run project in emulator, then from Eclipse choose menu Windows-> open perspective ->DDMS.
From tab device, choose emulator name, then go to file explorer,expand data->data->yourpackagename, you should see share reference xml file (only work on the emulator or a rooted device). Finally, export this file to windows.
See http://developer.android.com/tools/debugging/ddms.html
Update:
Another way, you can listen shared preference change:
SharedPreferences.OnSharedPreferenceChangeListener prefListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs,String key) {
if (key.equals("YourKey"))
{
//Get this
}
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.registerOnSharedPreferenceChangeListener(prefListener);
See SharedPreferences.onSharedPreferenceChangeListener not being called consistently
How to create, read and write a sharedPreferences file?
You can create SharedPreferences in you project without finding it in the project directory. This is actually stored in your project folder in the app file system once created (/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml).
But for creating, updating and retrieving you do not want to go there.
To Create SharedPreference
SharedPreferences.Editor editor = getSharedPreferences("MyPreference", MODE_PRIVATE).edit();
editor.putString("name", "Nathan");
editor.putInt("id", 1000);
editor.apply();
To retrieve
SharedPreferences prefs = getSharedPreferences("MyPreference", MODE_PRIVATE);
String name = prefs.getString("name", "Blank Name"); //"Blank Name" the default value.
int idName = prefs.getInt("id", 0); // 0 is the default value.
Please go through the below link for more details.
https://developer.android.com/reference/android/content/SharedPreferences?hl=en
How to use SharedPreferences in Android to store, fetch and edit values
To obtain shared preferences, use the following method
In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
I noticed, it is important to write difference between commit()
and apply()
here as well.
commit()
return true
if value saved successfully otherwise false
. It save values to SharedPreferences synchronously.
apply()
was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.
Related Topics
How to Create Colorstatelist Programmatically
Detect 7 Inch and 10 Inch Tablet Programmatically
Toolbar Overlapping Below Status Bar
Android Background Image Memory Usage
Disable Orange Outline Highlight on Focus
Fragments in Android 2.2.1, 2.3, 2.0. Is This Possible
Recyclerview Changing Items During Scroll
How to Display a List of Images in a Listview in Android
Can't Include C++ Headers Like Vector in Android Ndk
How to Add New Column to Android SQLite Database
Android + Pair Devices via Bluetooth Programmatically
Android Material: Status Bar Color Won't Change
How to Draw a Route, Along an Existing Road, Between Two Points
Write to /Res/Drawable/ on the Fly
Why Do Most Fields (Class Members) in Android Tutorial Start with 'M'