I wonder if any one can help me, i am trying to get my head around shared preferences, i assume they are stored in the device (tablet) and can be checked to see they exist.
My code below (first one) i want a button once clicked to put a string or boolean in the shared preferences.
The second code is to see if the shared prefs exist if it does make a settext change if not ignore and look for the next string
cala1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LoadPreferences();
SharedPreferences sharedpreferences = getSharedPreferences("prefman", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("cal1","c1");
editor.commit(); });
enter4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LoadPreferences();
SharedPreferences sharedpreferences = getSharedPreferences("prefman", MODE_PRIVATE);
sharedpreferences.contains("cal1");
if (sharedpreferences.getString("cal1","c1").equals("cal1"));
{
{cexist1.setText("Shared prefs exit");
}
else
I don't get why you call sharedpreferences.contains("cal1") when you ignore the return value anyway.
The Android documentation for SharedPreferences says the following:
contains(String key) Checks whether the preferences contains a
preference.
Looks like that is what you want, try using the call in you if clause.
if (sharedpreferences.contains("cal1")) {
cexist1.setText("Shared prefs exit");
}
the format of your code above is a bit messy too - makes it harder to read ;)
Related
In my app I was using for more than 1 year "Shared preferences" to store some boolean values (if the user has seen the intro page for example). Now I added one more setting (if the user has seen the help page!) and all the settings stopped working...
I tried changing "commit" to "apply" with no luck. How could by just adding one more shared preference to make it stop working? Is there any properties limit?
My code:
public SharedPreferences getSettings() {
SharedPreferences settings = getSharedPreferences(AppConstants.PREFS_NAME, 0);
return settings;
}
old Activity for Intro:
private void saveUserHasSeenIntro() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, true);
editor.commit();
}
where intro boolean is being read:
Boolean hasShownIntroSteps = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, false);
if ( !hasShownIntroSteps ) {
// show intro
} else {
New activity for help:
private void saveUserHasSeenHelp() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
}
where the "help" boolean is read:
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
if ( !hasSeenHelp ) {
// show help activity
} else {
Your methods are fine and they should work perfectly. Check a couple of things just in case:
Ensure you don't call clear() or remove() method of the SharedPreferences editor after saving your prefs by mistake.
Ensure the constants AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS and AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS have different values as the former could overlap the second by mistake.
Just add a breakpoint after setting the new pref and read the value to check if it's set just after it.
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
In some extreme cases you could even implement SharedPreferences.OnSharedPreferenceChangeListener to see where your SharedPreferences are being changed to avoid unwanted pref sets.
It can be a Memory Limitation on your SharedPreferences file and usually this comes with an OutOfMemoryException. I guess if something like that would happen you would probably seen it in your code, unless you are not reading/writing in another Thread. How big is your SharedPreferences file in numbers of key - value pair ?
I am using SWITCH (like android toggle button ) instead of normal buttons in my andorid app.
The code works fine while enabling and disabling switches.
But i want to store the state of the switch.
Suppose i enable the switch and close my application the background code will run fine but the switch state will change to disabled.
Every time when i close the application the switch state becomes disabled.
Is there any way to store the switch State??
Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.
The following might help you:
#Override
public void onClick(View v)
{
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
}
The final nail:
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}
Edit:
The above code is working, however I feel it is a bad practice to get the shared preference values in onCreate, its better to make a loader class which inits your app variables well beforehand in a separate thread.
Update: Wed 24 Jul; 2019:
Android has view model support now - this can be used to handle switch state and persist it across sessions or configuration changes.
SharedPreferences pref = getSharedPreferences("save",MODE_PRIVATE);
unit.setChecked(pref.getBoolean("first", false));
if(isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("save"MODE_PRIVATE).edit();
editor.putBoolean("first", true);
editor.apply();
unit.setChecked(true);}
else
{
SharedPreferences.Editor editor = getSharedPreferences("save",MODE_PRIVATE).edit();
editor.putBoolean("first",false);
editor.apply();
kilometer.setText("Km/h");
unit.setChecked(false);`enter code here`
}
Got this code, which basicly updates my textviews depending on how far the user is in the quiz, which is stored in sharedPrefs. But when the correct answer is entered the prefs doesn't update. Does the commit() need too long time to set the prefs, so the activity calls the method setText() before the sharedPrefs are updated or what am i doing wrong?
private void setText() {
SharedPreferences score = this.getSharedPreferences("football", MODE_PRIVATE);
questionNumber = score.getInt("football", 0);
question.setText(questions.get(questionNumber).get(0));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCheckAnswer:
if (questions.get(questionNumber).contains(etAnswer.getText().toString())) {
Integer newQ = questionNumber += 1;
SharedPreferences change = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = change.edit();
editor.putInt("football", newQ);
editor.commit();
setText();
}else{
question.setText("error occured");
}
break;
}
You're not opening the SharedPreference the same way when setting and getting.
Change this:
SharedPreferences change = this.getPreferences(Context.MODE_PRIVATE);
to this:
SharedPreferences change = this.getSharedPreferences("football", MODE_PRIVATE);
Notice the differences:
getPreferences vs getSharedPreferences
you didn't give the preference reference as "football"
Are you sure the prefs doesn't get updated or is it just that your textview isn't getting updated? If this is being done in your Activity, you should not be changing layout (your text view) from within the Activity. You should use a Handler to make UI changes.
I want to store my app data in a file so it could be accessed every time from the app - for example: money, user score, user current sprite...
I have never seen encryption in my life, and I wanted to know if there is an easy way to encrypt data and write it to the phone, and then decrypt it next time the app is open.
If there is no easy way, it would be great if someone could explain how the encryption/decryption works to me.
Use SharedPreferences.
I've used them, and you dont need to encrypt the data.
http://developer.android.com/guide/topics/data/data-storage.html#pref
EXAMPLE(from developer.android):
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
I know this has been asked a lot around SO, but I just can't seem to get this working.
Situation : I have a dialog with a EditText in it with an accept button. I would like to store the value of the string with SharedPreferences when the user touch the accept button. Here's the code I have so far.
public void showDialog()
{
final Dialog dialog = new Dialog(VentilationActivity.this);
dialog.setContentView(R.layout.menu_options);
dialog.setTitle("Configuration de l'adresse IP");
dialog.setCancelable(true);
dialog.show();
EditText adressIp = (EditText) dialog.findViewById(R.id.editText1);
SharedPreferences preferences = getSharedPreferences("Agrinuvo", 0);
String texte = preferences.getString("VentIpKey", "");
adressIp.setText(texte);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(adressIp, InputMethodManager.SHOW_IMPLICIT);
Button btnAccept = (Button) dialog.findViewById(R.id.button1);
btnAccept.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
EditText adressIp = (EditText) dialog.findViewById(R.id.editText1);
textIp = adressIp.getText().toString();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("VentIpKey", textIp);
editor.commit();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(adressIp.getWindowToken(), 0);
dialog.dismiss();
}
});
}
And, of course this is not working. Everytime I close the dialog window and reopen it the EditText text is empty. Thanks for any help you can provide.
How about;
public void showDialog() {
....
final SharedPreferences preferences = getSharedPreferences("Agrinuvo", 0);
....
#Override
public void onClick(View v) {
....
// Use previous preferences instance instead.
// SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("VentIpKey", textIp);
editor.commit();
....
}
}
}
Anyway, it seems so that you're writing to different preferences than where you read the default value from.
Inside your onClickObserver you create a SharedPreference object for a file named after your activity's class name. At least this is what the Activity's getPreferences(int) documentation states. Try instead initializing that object the same way you do it in showDialog or making the showDialog's preferences final.
It looks like there error might be inside your onclick method in the following line
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
If you change it to
SharedPreferences preferences = getSharedPreferences("Agrinuvo", Context.MODE_PRIVATE);
It should work. The way you were calling it, you weren't getting the same preference that you requesting for your dialog.
I've used preferences in my application without too many problems for quite a while and I would suggest a couple things:
getSharedPreferences() should only be used for preferences shared between different Activities. If only your one Activity will be using the data, use this to save:
SharedPreferences settings = getPreferences (MODE_PRIVATE);
SharedPreferences.Editor ed = settings.edit();
ed.putBoolean ("BooleanKey", booleanVar);
ed.putInt ("IntKey", intVar);
ed.putFloat ("FloatKey", floatVar);
ed.putLong ("LongKey", longVar);
ed.commit();
And this to retrieve:
SharedPreferences settings = getPreferences (MODE_PRIVATE);
longVar = settings.getLong ("longKey", 0);
...
If you're going to share your preferences across Activites, that's when you'll want to use getSharedPreferences(), but you'll want to NOT user MODE_PRIVATE. Currently, I use MODE_WORLD_WRITEABLE in the code where I write the data and MODE_WORLD_READABLE where I read it, that's probably not the best way (at least, the if the warnings I'm getting from Eclipse are to be believed).
Good luck,
R.