Reputation: 7905
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?
Upvotes: 6
Views: 5814
Reputation: 3999
Alternatively you can also use a tool like Facebook's flipper which, amongst other things, allows you to edit SharedPreferences live.
Note, you need to integrate it with your app. It's fairly straightforward though and can be done in such a manner, that release versions are not affected by it at all.
Upvotes: 1
Reputation: 10185
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.
AS will push that file back to the device.
Upvotes: 3
Reputation: 500
to access to shared preferences file that's identified by the resource string use the following code:
Kotlin:
var sharedPref = activity?.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE)
Java:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
it using the private mode so the file is accessible by only your app.
you can use the following code to write to sharedpref:
Kotlin:
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt("number", num)
apply()
}
Java:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("number", num);
editor.apply();
you can put boolean,string and etc to your sharedpref file.
then if you want to get that value you can say:
val num = sharedPref.getInt("number", defvalue = 0 )
as you know you can getBoolean, getString and etc
Refer documentation as well.
Upvotes: 1