Here is the code where I put the values:
if(soundima == 1){
soundima=0;
editor.putInt("sOn", soundima);
editor.commit();
}
else if(soundima == 0){
soundima=1;
editor.putInt("sOn", soundima);
editor.commit();
}
Then when I quit the application, the values are not remembered. I get the values with this code:
editor = PreferenceManager.getDefaultSharedPreferences(this);
soundima = editor.getInt("sOn", 0);
I am not entirely sure why that is not working. However, the following code should solve the problem.
//create a constant to use for the shared preferences
public static final String YOUR_CONSTANT = "Preferences";
Then to place the values in shared preferences, use the following code:
if(soundima == 1){
soundima = 0;
SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
SharedPreferences.Editor editor = sound.edit();
editor.putInt("sOn", soundima);
editor.commit();
}
else if(soundima == 0){
soundima = 1;
SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
SharedPreferences.Editor editor = sound.edit();
editor.putInt("sOn", soundima);
editor.commit();
}
Then to retrieve the values, use this code:
SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
soundima = sound.getInt("sOn", 0);
Related
I have two arrays, the first consists of 9 buttons. The second can hold 9 Strings. I have a method called getPlayerChoiceText to populate the String array with the text that is set on each button from the playerchoice Array. How can I save this text using SharedPreferences?
private String[] getPlayerChoiceText()
{
playerchoiceText[0] = playerchoice[0].getText().toString();
playerchoiceText[1] = playerchoice[1].getText().toString();
playerchoiceText[2] = playerchoice[2].getText().toString();
playerchoiceText[3] = playerchoice[3].getText().toString();
playerchoiceText[4] = playerchoice[4].getText().toString();
playerchoiceText[5] = playerchoice[5].getText().toString();
playerchoiceText[6] = playerchoice[6].getText().toString();
playerchoiceText[7] = playerchoice[7].getText().toString();
playerchoiceText[8] = playerchoice[8].getText().toString();
return playerchoiceText;
}
private void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
playerchoiceText = getPlayerChoiceText();
}
I have got the same problem. I solved it by using JSONArray.
JSONArray choices = new JSONArray();
choices.put("1");
choices.put("2");
choices.put("3");
// Save
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("choices", choices.toString());
// Retrieve
choices = new JSONArray(sharedPreferences.getString("choices", "[]"));
In this way, you can easily do Insert and Delete operations. I hope this helps.
Android's SharedPreferences operates as a key value store, and does not allow you to directly store Java objects. So, representing your player choice text values as a map would make more sense, if you want to store them using shared preferences.
There is one trick you might be able to use here, if you wanted to continue representing your choice texts as an array. You could store the texts using a delimiter, e.g. pipe:
String choices = String.join("|", playerchoiceText);
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
prefs.edit().putString("choices", choices).apply();
And then, on the way out:
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_KEY, Context.MODE_PRIVATE);
String[] playerchoiceText = prefs.getString("choices", "").split("\\|");
Use put/getStringSet():
private void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String[] playerchoiceText = getPlayerChoiceText();
editor.putStringSet("player_choice", new HashSet<T>(Arrays.asList(playerchoiceText));
editor.commit();
}
As i know the basic of save int value with sharedpreferences method is using this
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("savedscore", Score);
editor.commit();
and then we can get the int value in another activity using this
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
Score = pref.getInt("savedscore", 0);
Scoretext = (TextView)findViewById(R.id.textscore);
Scoretext.setText(String.valueOf(score));
and my question is how to totalize all the score that we got when we playing in another activity?
example ;
when i play for the first time i got the score 4000 , so of course when we use this method editor.putInt("savedscore", Score); it will save the score value and then we got the score value in another activity with using this Score = pref.getInt("savedscore", 0); it will make the int Score value to 4000
and then i play again then i got score 2000 , so of course the sharedpreferences Score = pref.getInt("savedscore", 0); int Score value will change to 2000 and not totalize
so that is my question how to Totalize the score?
Simply create another preference entry "totalScore" and increment it accordingly (each time you save a new score):
//...
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("savedscore", Score);
editor.commit();
updateTotalScore(Score)
//..
private void updateTotalScore(int newScore){
SharedPreferences pref = getSharedPreferences("totalScore", MODE_PRIVATE);
int current = pref.getInt("totalScore", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("totalScore", current+newScore);
editor.commit();
}
private int getTotalScore(){
SharedPreferences pref = getSharedPreferences("totalScore", MODE_PRIVATE);
return pref.getInt("totalScore", 0);
}
Whats wrong with the below code
I am not able to retrieve a simple setting saved in SharedPreferences. s1 is always "". What it the small mistake I am doing >
SharedPreferences sp = getSharedPreferences("MyTestPref", 0);
String s = "Item1";
sp.edit().putString("VAL", (s));
sp.edit().apply(); //also tried commit
String s1 = (sp.getString("VAL", ""));
It should be like this:
String s = "Item1";
sp.edit().putString("VAL", (s));
sp.edit().commit(); //also tried commit
String s1 = (sp.getString("VAL", ""));
use commit() not apply().
EDIT:
final String PREFERENCE_NAME = "your_pref";
String s = "Item1";
SharedPreferences preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("VAL", s);
editor.commit();
String s1 = preferences.getString("VAL", "");
I need the inserted values in this edittext to show up after i quit the application. I currently have it set up so it'll set new default values if this is the first time for a user to set up the settings page but i can't get the set values to save and load the same values. Here is my code.
if (res.equals("555")) {
//post the saved text
} else if (res.equals("510")) {
editTextname.setText("Firstname Lastname", TextView.BufferType.EDITABLE);
editTextphone.setText("XXX-XXX-XXXX", TextView.BufferType.EDITABLE);
editTextemail.setText("name#yourdomain.com", TextView.BufferType.EDITABLE);
editTextaddress.setText("Street, City, State, Zip", TextView.BufferType.EDITABLE);
//save the entered text above and show it
}
Use SharedPreferences:
SharedPreferences prefs = getSharedPreferences("MyPreference", MODE_PRIVATE);
// On first run:
SharedPreferences.Editor editor = prefs.edit();
if(!prefs.contains("key1"))
editor.putString("key1", "defaultValue1");
if(!prefs.contains("key2"))
editor.putString("key2", "defaultValue2");
editor.commit();
// On save:
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value3");
editor.commit();
// On read:
String value1 = prefs.getString("key1");
String value2 = prefs.getString("key2");
For the life of me I cannot figure out why I can’t get this method to enter the if statement.
protected void foo() {
Date d = new Date();
long now = d.getTime();
long start;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
start = settings.getLong(FIRST_USE_DATE, 0);
Log.w(this.getClass().getName(), Long.toString(start));
if (start == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
}
return true;
}
Note that the log and debug mode shows that “start = 0”
I also tried
if (start == 0l) {
if (start == 0L) {
What the heck am I missing here? Does 0 != 0?
I’m developing in Eclipse with Java for Android. Thanks.
Edits:
#methodin - no sorry, that does not work.
#Aioobe - I have a breakpoint under the IF statement, that never gets made.
Edit2: Here is the actual code I'm running since you've asked.
protected boolean isDemoExpired() {
Date d = new Date();
long now = d.getTime();
long demoStart;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
demoStart = settings.getLong(FIRST_USE_DATE, 0);
if (demoStart == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
System.out.println(Long.toString(demoStart));
return false;
}
return true;
}
I think your problem is exactly the opposite.
I've just debugged your code and it works, the problem is that the if statement it's always true because there's no editor.commit() after making the changes to the FIRST_USE_DATE variable.
protected void foo() {
Date d = new Date();
long now = d.getTime();
long start;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
start = settings.getLong(FIRST_USE_DATE, 0);
Log.w(this.getClass().getName(), Long.toString(start));
if (start == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
***editor.commit();***
}
}
Edit: I've just tried debugging your actual code and the same thing happened: the if statement it's always true and it gets made every time because there's no editor.commit() to save the changes to the FIRST_USE_DATE variable.
protected boolean isDemoExpired() {
Date d = new Date();
long now = d.getTime();
long demoStart;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
demoStart = settings.getLong(FIRST_USE_DATE, 0);
if (demoStart == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
****editor.commit();****
System.out.println(Long.toString(demoStart));
return false;
}
return true;
}
Why won't you use Long start instead of long and check for null value?
protected void foo() {
Date d = new Date();
long now = d.getTime();
Long start;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
start = settings.getLong(FIRST_USE_DATE, 0);
Log.w(this.getClass().getName(), Long.toString(start));
if (start == null) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
}
}
it seems that auto-unboxing is happening here and you get zero value. Another question is why 0 == 0 check doesn't pass.
You are making a mistake somewhere...
Are you sure you are not entering the if statement AND that start = 0 ?
Are you showing us the code you are running ?
You could execute following code (equivalent to your code)
public static void main(String[] args) {
long start = 0;
if (start == 0) {
System.out.println(Long.toString(start));
}
}
And you'd see you enter the if statement...
Are you familiar with the concepts of hiding and shadowing? Do you have any other variables using the same names in this class or one of its parents?
I don't think there is anything wrong with your code - try rebooting your computer (its a Microsoft OS right? :)
If that don't work delete the offending code (end up with an empty method) compile and test to ensure there are no bugs. Then hardcode an acceptable value and test again. Finally retype your code - do not paste a copy.
Once, a very long time ago, I had something similar and it did not go away until I re-entered the code - my best guess is some hidden character was causing problems, but I have never seen it again (nor am I certain what the hell happened that time either).