getSharedPreferences not returning a value - android

I've placed a preferences file 'xml/sleeppreferences.xml' into a tabSpec, with the idea that that is the preferences for that part of the app and there will be other preference files for other parts.
This seems to work ok. I make a preference change, close the emulator, re-run the app, go back to the preference page, and the preference is what I had set it to.
But when I click to another tab, where I want to use the value of that preference, it all goes wrong.
I've looked high and low, but cannot find an answer.
This is an excerpt of the code:
public static final String PREF_FILE_NAME = "sleeppreferences";
:
:
:
SharedPreferences prefs = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
String test=prefs.getString("editTextPref", "unset");
with "unset" being the default response if it doesn't find anything.
It always returns "unset"
As I say, I've looked all over, and the code I'm using seems to be the correct code. So what's going on?
Thanks
Dave

Try using the GetSharedPreferences of the context class. Something like this:
public String GetPassword (Context Contexto, String Key) throws Exception
{
SharedPreferences savedSession= Contexto.getSharedPreferences(Key,Context.MODE_PRIVATE);
return Encryption.decrypt(_Seed,savedSession.getString(Key, null));
}
I think this should work as well:
getApplicationContext().getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE).getString("editTextPref", "unset");

Please, try this code to save your preferences and then use the code I previously pasted. It has to work fine.
SharedPreferences savedSession= context.getSharedPreferences(Key,Context.MODE_PRIVATE);
Editor editor = savedSession.edit();
editor.putString(Key, EncryptedPass);
editor.commit();

Related

Where to put file for storing sharedpreferences

I want to utilize the sharedpreferences in my app, but in all of the tutorials and documentation in the internet I can not find out where to put the file that I am suppose to use.
What I mean is, when trying to access it as so:
public static final String PREFS_NAME = "AOP_PREFS";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
I don't know where to put the file AOP_PREFS.xml so that my class can use it. Am I missing something and I'm not suppose to be creating a file?
I don't quite understand what you are trying to do here. If your code is in an activity class, you just need to call getSharedPreferences(int) instead of getSharedPreferences(String, int). You get the preferences like this:
SharedPreferences prefs = getSharedPreferences (Context.MODE_PRIVATE);
Or you can use the PreferenceManager class to get the shared preferences as well:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
where this is a Context object.
You can retrieve a string from the preferences using a key (In this case, myString).
prefs.getString ("myString", "");
If you have not saved a string with the myString key, the second parameter will be returned.
This is how you can save a string into the preferences:
prefs.edit().putString ("myString", "Some String value");
The first parameter is the key, and the second is the value. Self-explanatory!
NOW REMEMBER! Every time you save something, call apply()!
prefs.edit().putString ("myString", "Some String value").apply();
*******
And that's all you have to know about shared preferences!
Using SharedPreferences, the file is automatically created in the files folder in internal storage of your app, so you don't need to explicitly do anything to create the file.
The file in this case will be AOP_PREFS.xml.
You can also just use "default" SharedPreferences, which will be stored in an xml file with the package name of your app.
Example of Writing to Default SharedPreferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("some_value", someValue);
editor.commit();
Reading:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Long someVal = sp.getLong("some_value", 0);
Note that unless you have a rooted device, you won't be able to view files in internal storage.

Shared Preference returns always the default value

Here is code I am Using to create and store value in Preference.
outgoing is String variable.
SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("PhoneNo","Hi");
editor.commit();
Here is the code to get value from SharedPreference.
SharedPreferences sp
=getSharedPreferences(outgoing,Activity.MODE_PRIVATE);
String calln = sp.getString("PhoneNo","0");
Toast.makeText(mContext, "SHARED"+calln,Toast.LENGTH_LONG).show();
You should probably call the getSharedPreferences on the context from which you are accessing them.
Source
Therefore, depending on how you can access your context, if you pass it to some other activity or in an asynchronous task, here are some examples of usage:
this.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
context.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
Also, one way you can test your stuff is to use a listener when SharedPreferences get changed:
onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
Called when a shared preference is changed, added, or removed.
here is how to do that
You can also use the Preference Manager to obtain the SharedPreferences:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).getString(
"PhoneNo", "0");
Or to store them:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).edit().putString(
"PhoneNo", "Hi").commit();
The most likely reason that Shared Preference always returns the default value is that you saved the value in one preference file and then tried to retrieve it in another preference file. This can happen if you do call getPreferences() from different Activities, because getPreferences() creates a different preference file based on the activity it is created in.
Solution
The easiest solution is to always get your shared preferences like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
This will use a single preference file for the entire app.
Alternate solution
If for some reason you need to use different preference files, then you can do
final static String PREF_FILE_1 = "pref_file_1";
...
SharedPreferences sharedPref = context.getSharedPreferences(PREF_FILE_1, Context.MODE_PRIVATE);
Just make sure you always use the right file name for the preferences you are trying to save and retrieve.
Local preferences
If you really only need a preference for a specific Activity, then you can use getPreferences(Context.MODE_PRIVATE). Just don't expect to be able to retrieve the values from another Activity in the same way.
See also
This answer describes the differences between the various ways of obtaining SharedPreferences.
Difference between getDefaultSharedPreferences and getSharedPreferences
Mess with the shared preferences of android - which function to use?
change this Activity.MODE_PRIVATE to this Activity.MODE_MULTI_PROCESS, issue is probably due to different context during storing value and accessing value.
When putting values, try changing this:
SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
to this:
SharedPreferences sp = getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
Same when getting values - don't forget to add getApplicationContext() in your call to SharedPreferences
EDIT:
Check that your "outgoing" String is the exact same in both Activities

Set<String> in android sharedpreferences does not save on force close

Im trying to use androids sharedpreferences, I´ve logged everything and the code below really commits the string set. The problem is when I force close the app and start again, the settings.getStringSet returns an empty set. No errormessages anywhere.
I´ve tried PreferenceManager.getDefaultSharedPreferences but that does not work for me either.
Thanks for you time.
public static final String PREFS_NAME = "MyPrefsFile";
private static final String FOLLOWED_ROUTES = "followedRoutes";
and later on when saved is called:
public void onFollowClicked(View view){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> follows = settings.getStringSet(FOLLOWED_ROUTES, new HashSet<String>());
follows.add(routeId);
editor.putStringSet(FOLLOWED_ROUTES, follows);
editor.commit();
}
You can also work around the bug mentioned by g00dy this way:
Get the set from sharedPreferences and save it in a variable.
Then just delete the set in sharedpreferences before adding it again when saving.
SharedPreferences.Editor editor= sharedPref.edit();
editor.remove("mSet");
editor.apply();
editor.putStringSet("mSet", mSet);
editor.apply();
Make sure to use apply() or commit() twice.
Alternatively, if you are working in Kotlin simply :
PreferenceManager.getDefaultSharedPreferences(applicationContext)
.edit {
this.remove("mSet")
this.apply()
this.putStringSet("mSet", mSet)
}
Take a look here.
Also for refference:
SharedPreferences
SharedPreferences.Editor
EDIT:
There's actually a bug with this one, see here. An extract from there:
This problem is still present on the 17 API level.
It is caused because the getStringSet() method of the
SharedPreferences class doesn't return a copy of the Set object: it
returns the entire object and, when you add new elements to it, the
commitToMemory method of the SharedPrefencesImpl.EditorImpl class see
that the existing value is equal to the previous one stored.
The ways to workaround this issue is to make a copy of the Set
returned by SharedPreferences.getStringSet or force the write to
memory using other preference that always change (for example, a
property that stores the size of the set each time)
EDIT2:
There might be a solution here, take a look.

checkbox value in other activity

hy, everyone
i'm searching for a few days a solution for one problem i tried to search but i didn' find an answer for my problem so i decided to ask you maybe someone it will so kind and wil explaine to me ho can solve my problem.
So i have two activities, a configure one and a main one, my problem is that when i check one checkbox in the configure activity (i succeed to save the checkbox state so when i check it will be checked even if i leave the configure activity), but i don't know how can i use the checkbx state in the main activity. i found many suggestions but for for me nothing worked.
thank you in advance.
thank you for all for the answers but i not succeeded in this way to solve my problem, and with your suggestions i did the following: in the second activity(where i have the CheckBox): i have one Save function where i save with SharedPreferences the Checkbox State( even if i close the activity or anything else the state of Checkbox it's keeping his state) and i have made a Load function where when i load back the activity it's loading the previous state so inside this activity i thing it is ok, But in this case how can use the load function's value (in fact the checkbox value) int the MainActivity.
I'm sorry for inconvenience but i'm knew but i would like to learn.
Thank you ones again.
Store the value in SharedPreference to get the value of checkbox
chkIos.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
SharedPreferences sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString("checkboxState",((CheckBox) v).isChecked());
editor.commit();
//Save the state of checkbox in sharedPreference
}
}
});
In main activity get the state like this.
SharedPreferences sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
String stateValue = sharedPreferences.getString("checkboxState);
i guess the sharepreferences will resolve that
SharedPreferences.Editor editor = app_preferences.edit();
editor.putBoolean("Checkbox", value);
editor.commit();
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
boolean value = app_preferences.getBoolean("Checkbox", false);
You can use SharedPreferences to save the state of your CheckBox in the device so you can retrieve it from another Activity.
Here is an example how to use them. Also you can check this YouTube video that shows you how to make preferences screen for your Activities.

How to check if a FileInputStream is "full"

I'm trying to write a file on users mobile following this example
Storage Options [data-storage]
I want to create that file the first time users run my app.
After the first time users run my app, I want FIRST read the file, and THEN write something in it (if i need).
Following the example above i'm using FileInputStream stream= openFileInput(FILENAME),
Is there a way to know if the file i put in FileInputStream exists by checking the fIleInpuStream itself?
Thank everybody for your help.
Maybe the best way to do what i want to do was suggested by #Durairaj P.
I used Preferences.
But i'm still wondering if it's suitable and appropriate for what i want to do. I want to keep track of the points that users earn while playing my game; when users re-open my app, i have to show all the points they earned since they installed my app. I'm just wondering if Preferences are suitable and appropriatefor this, or if i should use something else.
Anyway i post my code, it might help someone
public class managePreferences{
Context context;
managePreferences(Context context){
this.context = context;
}
public String readPreference(String fieldName, String defaultValue){
SharedPreferences prefs = context.getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
String value = prefs.getString(fieldName, defaultValue);
return value ;
}
public void writePreference(String fieldName, String value){
SharedPreferences prefs = context.getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(fieldName, value);
editor.commit();
}
}
I would use
context.fileList();
and test if my file is somewhere. (quickest way is to make a List of it and use contains()) :
Arrays.asList(context.fileList()).contains(FILENAME);

Categories

Resources