Android SharedPref edit not working - android

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.

Related

SharedPreferences saves state between android activities but not upon restarting the app

I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.

Android SharedPreferences update does not work

I know, this issue has been dealt with in many threads, but I cannot figure out this one.
So I set a shared preference like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.apply();
I read the preferences like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = null;
spinnerValuesSet = prefs.getStringSet(spinnerName,null );
Everything works, except for my changes are visible while this activity runs i.e. - I display the values from the SharedPreferences, allow the user to delete or add and then update the ListView. This works, but after I restart the application, I get the initial values.
This for example is my method to delete one value from the list, update the values in SharedPreferences and update the ListView
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
for (String s : spinnerValuesSet)
{
if(s == currentSelectedItemString)
{
spinnerValuesSet.remove(s);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, spinnerValuesSet );
editor.apply();
break;
}
}
updateListValues();
}
});
And this is the method that updates the ListView:
private void updateListValues()
{
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
if(spinnerValuesSet.size() > 0)
{
names = new ArrayList<String>();
names.clear();
int k=0;
for (String s : spinnerValuesSet) {
names.add(k, s);
k++;
}
namesAA = new ArrayAdapter<String> ( this, android.R.layout.simple_list_item_activated_1, names );
myList.setAdapter(namesAA);
}
}
Any help is much appreciated.
The Objects returned by the various get methods of SharedPreferences should be treated as immutable. See SharedPreferences Class Overview for reference.
You must call remove(String) through the SharedPreferences.Editor returned by SharedPreferences.edit() rather than directly on the Set returned by SharedPreferences.getStringSet(String, Set<String>).
You will need to construct a new Set of Strings containing the updated content each time since you have to remove the Set entry from SharedPreferences when you want to update its content.
Problem happens because the Set returned by SharedPreference is immutable. https://code.google.com/p/android/issues/detail?id=27801
I solved this by created a new instance of Set and storing in all the values returned from SharedPreferences.
//Set<String> address_ids = ids from Shared Preferences...
//Create a new instance and store everything there.
Set<String> all_address_ids = new HashSet<String>();
all_address_ids.addAll(address_ids);
Now use the new instance to push the update back to SharedPreferences
I may be wrong but I think the way you are retrieving the Shared Preferences is the problem. Try using
SharedPreferences prefs = getSharedPreferences("appPreferenceKey", Context.Mode_Private);
Use editor.commit(); instead of editor.apply();
Example Code:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.commit();
I hope this helps.
Depending on the OS Build you may have to save values in a different way.
boolean apply = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
public static void saveValue(SharedPreferences.Editor editor)
{
if(apply) {
editor.apply();
} else {
editor.commit();
}
}

Android Shared Preferences Saving Highscore and Unlocks

I have 27 characters that I want a player to unlock by beating scores, e.g. if his score is greater than 200 he unlocks character #1. I have a hard time trying to do that.
I have a class for characters that contains its number, the score required to unlock it, and a boolean to check if he is unlocked. But when it comes down to saving, I can't do that.
The main game loop is in file GameScreen. It has a value points counting the score.
When GameState changes to PlayerDead I want to check if any new character has been unlocked, and whether the high score has been beaten to save points.
Please help, I'm struggling with it for over a week and I can't find a good tutorial for SharedPrefs because all of them apply to GUI based activity that saves the name and surname you entered.
if you need sharedPrefs I can help you.
I can give some some example code.
or you can send your code and error if you get one, we update it.
but sharedPrefs is a good idea for that ? if user goes to application settings and clears data of your app, all data will be lost.
why dont you try create a sqlite databade, save it into assets directory and use it?
It's actually pretty simple, you use SharedPreferences to store key-value pairs. You can either call
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
From the GameScreen and then define a constant:
public static final String KEY_SCORE = "score";
To use as the key for the saving.
In order to actually save, you need an Editor:
SharedPreferences.Editor mEditor = mPrefs.edit();
//save data now, mPlayerScore is the score you keep track of
//if it's another type call putString(), etc
mEditor.putInt(KEY_SCORE, mPlayerScore);
//if that is the only thing you want for noe
//close and commit
mEditor.commit();
And in order to retrieve the saved score, during your onCreate() you can do:
public void getUserProgress() {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//no need for an editor when retrieving
mPlayerScore = mPrefs.getInt(KEY_SCORE, 0);
//second value passed was the default score
//if no score was found
}
In order to check for new character s being unlocked, you can call the following code after every game:
private void checkForUserUnlocks() {
if (mPlayerScore >= MyUnlockableCharacter.SCORE_NEEDED_TO_UNLOCK)
MyUnlockableCharacter.isUnlocked = true;
//and same for other unlockabld characters
}
There are other ways to access SharedPreferences, let me know if you need more info.
Use the below code to store and retrieve Score from SharedPreference.
public static void saveScore(Context context, int score){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("SCORE", value);
editor.commit();
}
public static int loadScore(Context context){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
int score = sharedPreferences.getInt("SCORE", 0);
return score;
}
Read Sample;
public int Read() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
int mCounter = mSharedPrefs.getInt("Counter", 0);
return mCounter;
}
Write Sample;
public void Write() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
mPrefsEditor.putInt("Counter", 15);
mPrefsEditor.commit();
}

Shared Preferences is not retaining anything

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.

Need to check if Shared Preferences String or Boolean exist

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 ;)

Categories

Resources