How to access flutter Shared preferences on the android end (using java) - android

I have the following function in dart to set a particular boolean preference value.
_switchPersistentNotifications() {
setState(() {
isPersistentNotificationEnabled = !isPersistentNotificationEnabled;
});
widget.preferences.setBool(
"isPersistentNotificationEnabled", isPersistentNotificationEnabled);
}
This function sets the value of isPersistentNotificationEnabled preference.
Now on the native android end, I am supposed to use this shared preference value. Here's what I have done so far.
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// check if the state change notification is to be shown
if (preferences.getBoolean("flutter.isStateChangeNotificationEnabled", false)) {
showConnectionStateChangeNotification();
}
And the if condition never gets evaluated to true. I also tried printing all the existing preference values using the code below.
Map<String, ?> allEntries = preferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
And it only presents the values that the Android has created (using java).
Any help in accessing the preference values is greatly appreciated.
Thank You.

Sorry this answer is coming late, just got the answer from flutter github page.
What you can do to accomplish this is:
SharedPreferences prefs = getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE);
then if you want to read e.g. "myValue" key, you have to add "flutter." prefix:
String value = prefs.getString("flutter."+key, null);

Related

How to access Shared Preferences data saved by flutter? [duplicate]

I have the following function in dart to set a particular boolean preference value.
_switchPersistentNotifications() {
setState(() {
isPersistentNotificationEnabled = !isPersistentNotificationEnabled;
});
widget.preferences.setBool(
"isPersistentNotificationEnabled", isPersistentNotificationEnabled);
}
This function sets the value of isPersistentNotificationEnabled preference.
Now on the native android end, I am supposed to use this shared preference value. Here's what I have done so far.
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// check if the state change notification is to be shown
if (preferences.getBoolean("flutter.isStateChangeNotificationEnabled", false)) {
showConnectionStateChangeNotification();
}
And the if condition never gets evaluated to true. I also tried printing all the existing preference values using the code below.
Map<String, ?> allEntries = preferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
And it only presents the values that the Android has created (using java).
Any help in accessing the preference values is greatly appreciated.
Thank You.
Sorry this answer is coming late, just got the answer from flutter github page.
What you can do to accomplish this is:
SharedPreferences prefs = getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE);
then if you want to read e.g. "myValue" key, you have to add "flutter." prefix:
String value = prefs.getString("flutter."+key, null);

editor.remove() in sharedpreferences not removing the key

I have experienced a strange behavior that does not make any sense to me.
I have managed to save a value of temperature in sharedpreferences in a Java Class that is not an activity by doing this:
The method getContextOfApplication() is the one I am using in my Java.Class where i am putting the value of a temperature in a String and storing it in sharedpreferences as "temperature".
This method is declared in my MainActivity like this:
public static Context contextOfApplication;
public static Context getContextOfApplication() {
return contextOfApplication;
}
This method getContextOfApplication(); is the used in all assosiacions with sharedpreferences, in Mainactivity and in my Java.Class
tempParsed = Jobject.get(("temp")) + "";
SharedPreferences tempSettings = getSharedPreferences(getContextOfApplication());
SharedPreferences.Editor tempEdit = tempSettings.edit();
tempEdit.putString("temperature", tempParsed);
tempEdit.apply();
And later I recieve this value of the key "temperature" in my MainActivity like this:
SharedPreferences fetchSettings =
PreferenceManager.getDefaultSharedPreferences(getContextOfApplication());
String Temp = fetchSettings.getString("temperature", "");
And I can use the stored temperaure with the String Temp.
So far so good.
Later on in my code I wanted to delete this string in that is saved in sharedpreferences with the key "temperature".
Easy I thought...
First I called this code when I wanted to delete the value / values
SharedPreferences fetchSettings =
PreferenceManager.getDefaultSharedPreferences(getContextOfApplication());
SharedPreferences.Editor editor = fetchSettings.edit();
editor.clear();
editor.apply();
But this code deletes ALL information that is stored, so I obvously didn't want that.
That's why I tried to change this line:
editor.clear();
editor.apply();
To this:
editor.remove("temperature")
editor.apply();
But this didn't work!!
Now you are probably wondering "Are you sure that is what your key is named?"
I added this code to read all entries that were stored in the defaultsharedpreferences:
Map<String, ?> allEntries = fetchSettings.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("mapvalues ", entry.getKey() + ": " + entry.getValue().toString());
}
AND THE LOG SHOWS "temperature:" as the key....
Why is editor.clear(); working but editor.remove("key") is not?
According to the docs you need to call commit for the changes to happen:
editor.remove("temperature").commit();
Solved
You can try this code for remove single preference:
Prefs.remove("my_custom_key");
Don't forget to import library:
import com.pixplicity.easyprefs.library.Prefs;
This code worked for me Beautifully.

Increment shared preference key after adding value

In my app, the user can add a name and an age for multiple people. Most likely it will only be around 2 or 3. I want to store these in shared preferences. I set a counter to keep track of how many people have been stored as well as to manage which key goes with which value. I took the edittext input and put it in a string and then put it into the shared preferences like so, adding on the counter so I know that is the first person and would access the person with "name1".
//this is in the class
public int count = 1;
//this is in the main
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
Unless I am mistaken, that should put the string "name" into "Name1".
Then I go and try to access it in another activity with...
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("Name"+count,"");
String age = sharedPreferences.getString("Age"+count,"");
Then i would update the counter before the next person would be added to change the key to "Name2" "Age2", and so on.
Whenever I try to set the strings to a textview, they show up blank. Which means its not the same String to access the key. The putString has to get the "Name1", because even when I try to access the getString("Name",""), it's still blank. Is there something I'm doing wrong or missing. Or there is a better way of doing this? Thanks.
SharedPreferences sharedPreferences = getSharedPreferences("registerData",Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
myEditor.apply();//returns nothing,don't forgot to commit changes
also you can use
myEditor.commit() //returns true if the save works, false otherwise.
Is there something I'm doing wrong or missing. Or there is a better
way of doing this?
If SharedPreferences key names are dynamic then you should use SharedPreferences.getAll() which return all keys available in selected preference:
Map<String, ?> allKeys = sharedPreferences.getAll();
Now iterate through allKeys to check key names and get values from Map.Entry related to key like:
for (Map.Entry<String, ?> entry : allKeys.entrySet()) {
Log.v("TAG","Key Name :" entry.getKey());
Log.v("TAG","Key Value :" entry.getValue());
}
You have to call apply() on the shared preference editor after making changes.
...
myEditor.apply();
Shared preferences however, are not meant to store content related data. Consider using more appropriate solutions like a database.

How to get all keys of SharedPreferences programmatically in Android?

How to get all keys in SharedPreferences, not the value of the preference just key only?
prefA = getSharedPreferences("MyAttack", MODE_PRIVATE);
prefB= getSharedPreferences("MySkill", MODE_PRIVATE);
SharedPreferences has the method getAll() that returns a Map<String, ?> . From the Map you can retrieve easily the keys with keySet() and the key/value mappings with entrySet():
Map<String, ?> allEntries = prefA.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
What you can do is use getAll() method of SharedPreferences and get all the values in Map and then you can easily iterate through them:
Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
For more, you can check PrefUtil.java's dump() implementation with this link.
Use the getAll() method of android.content.SharedPreferences.
Map<String, ?> map = sharedPreferences.getAll();
Kotlin will allow you to get all your SharedPreferences keys with just one line by using Map.
Cheers mate 🎉
val sharedPreferences = context.getSharedPreferences("SHARED_PREFERENCES", Context.MODE_PRIVATE)
val sharedPreferenceIds = sharedPreferences.all.map { it.key } //returns List<String>
Check out the below code for getAll() method
Map<String, ?> prefsMap = prefA.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
Log.v("SharedPreferences", entry.getKey() + ":" +
entry.getValue().toString());
}
After reading #Delacrix response and playing with the Kotlin-way (tested in Kotlin 1.3.11) of retrieving the keys, I found out an even shorter version for getting the keys (or even the values):
val prefsA = context.getSharedPreferences("MyAttack", Context.MODE_PRIVATE)
val prefsAIDs = sharedPreferences.all.keys //returns MutableSet<String>
The same way, you can access only the values via sharedPreferences.all.values (even tho is not what you asked in your question, might be a useful for other readers).
Although #Blackbelt's answer is quite popular here, I think it is not actually targeting the question. (It is not suprising since the question mixes up the terminology of preferences names and keys.) I guess the question is how to find out which shared preferences instances have been created - which can be of interest if the names are created dynamically.
Here are two strategies for that:
create another shared preferences "meta" instance where all created shared prefences instances are registered by adding a key/value pair for it to the meta prefs - with the key being the shared prefences name and the value being any value e.g. true.
getSharedPreferences( DYNAMIC_PREFS_NAME, 0 )
.edit().put*(*).apply();
getSharedPreferences( "meta_prefs_index", 0 )
.edit().putBoolean( DYNAMIC_PREFS_NAME, true).apply();
To obtain all shared prefences created by you, use the meta prefs and follow the answer of #Blackbelt.
shared preferences have a backup file, which is stored in folder /data/data/YOUR_PACKAGE_NAME/shared_prefs with name YOUR_PREFS_NAME.xml
So you can look into that directory for your shared preferences files. But be careful, there might be shared preferences files that were not created by your logic! Therfore I would stick with the first approach.

How to iterate through all keys of shared preferences?

SharedPreferences have method getAll, but it returns no entries despite the fact some keys exist:
PreferenceManager.getDefaultSharedPreferences(this).contains("addNewAddress");
returns true
Map<String, ?> keys=PreferenceManager.getDefaultSharedPreferences(this).getAll();
returns empty map
What is wrong? How to get list of all shared preferences?
What you can do is use getAll() method of SharedPreferences and get all the values in Map<String,?> and then you can easily iterate through.
Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " +
entry.getValue().toString());
}
For more you can check PrefUtil.java's dump() implementation.
i think the question has more to do with why
PreferenceManager.getDefaultSharedPreferences(this).getAll()
is returning an empty/contradictory map than with how to iterate over a standard java map. the android doc isn't really crystal clear about what's going here but basically it seems like the first call ever to
PreferenceManager.setDefaultValues(this, R.xml.preferences,false)
-- which is what you're supposed to call to initialize preferences when you start your app -- creates some kind of cached version of your preferences which causes future changes to your xml preferences file to be inconsistently handled, i.e., causing the mismatch you described in your question.
to reset this "cached entity", follow these steps (which you can sort of come up with from the above link):
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().clear();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
incase anyone wants to iterate through sharedpreferences in KOTLIN
sharedPreferences?.all?.forEach {
//access key using it.key & value using it.value
Log.d("Preferences values",it.key() + ": " + it.value()
}
In Kotlin is very easey, you can change FILE_PREF_XML for you preferences file
getSharedPreferences("FILE_PREF_XML", Context.MODE_PRIVATE).all?.forEach {
Log.d(TAG,"shared pref(" + it.key + ") = " + it.value)
}

Categories

Resources