Couldn't save "long" in Shared Preference - java

I am saving "long" in Sharedpreferences as below :
SharedPreferences preferences = context.getSharedPreferences("STARTTIME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("startTime", startTime);
editor.commit();
and Retreiving "long" from Sharedpreference as below :
preferences = context.getSharedPreferences("STARTTIME", android.content.Context.MODE_PRIVATE);
long getstartTime = preferences.getLong(startTime, 0);
But I am getting value "0" while retreiving.....Any guess where am i making mistake ?

This:
long getstartTime = preferences.getLong(startTime, 0);
should be
long getstartTime = preferences.getLong("startTime", 0);
Android interpreted the startTime as a resource id, and because it didn't find it, you get the default value, that you passed in, as returnvalue.

You should pass the same key to the getLong() method i.e. literal "startTime" .
long getstartTime = preferences.getLong("startTime", 0);

Related

SharedPreferences editor not executing

In the following piece of code, one of the mEditor lines, doesn't appear to execute.
I've tried many different combinations so far, but can't get it to execute properly. The value is not set at all.
If i try to use the value, like in a Toast, I will receive a ResourcesNotFound Exception
Initialization of SharedPreference in my onCreateView, Fragment
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSharedPreferences.edit();
public void onClick(View view) {
int round_number = mSharedPreferences.getInt(getString(R.string.pref_round_played),0);
if (round_number == 0){
game_team.setBackgroundResource(R.drawable.t);
game_team.setVisibility(View.VISIBLE);
knap_bund.setVisibility(View.INVISIBLE);
knap_top.setText("Next Strat");
mEditor.putString(getString(R.string.pref_chosen_team), "T");
mEditor.putInt(getString(R.string.pref_round_played),round_number + 1);
mEditor.apply();
//Show CT side Pistol round here//
}
Following code is used in my onClick, which has other sharedPreferences, working the exact same way, which executes fine.
The first line executes just fine, but the second line containing 'putInt' isn't executing as intended.
mEditor.putString(getString(R.string.pref_chosen_team), "T");
mEditor.putInt(getString(R.string.pref_round_played), 1);
mEditor.apply();
Example of working code:
else if(round_number <= 30){
mEditor.putInt(getString(R.string.pref_round_played),round_number + 1);
mEditor.apply();
}
UPDATE
Just to clarify due to the comments. It's only this one occasion where the sharedPreferences won't work. I use it about 15 other places in this fragment, with no issues at all
I will receive a ResourcesNotFound Exception
I think R.string.pref_round_played is not exist,check it for your strings.xml
you're not posted for your detailed code so do it like this below to save values in shared preference
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME , MODE_PRIVATE).edit();
editor.putString("name", "john");
editor.putInt("id", 123);
editor.apply();
Retrieve the data from shared preference
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", ""); // you can put default value if you need
int idName = prefs.getInt("id", 0);
if this is not works for you please post your full code
Update
change your code to this one
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mEditor = mSharedPreferences .edit();

Passing variables through many activities

on MainActivity I have two edit texts which I get name and age values
now I have in this activity for example name="Mohamed" age=26
my questions is how to use these variables freely in other activities without passing them through Intent
Use the Shared Preferences.
Set the values:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", name);
editor.putInt("age", age);
editor.commit();
Retrieve values:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredName = prefs.getString("name", null); //null is the default value.
int age = prefs.getInt("age", 0); //0 is the default value.
For more information visit Android Doc Shared Preferences

Preferences always returns default value

This code I use to create value in SharedPreference.
SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("ans1",1).commit();
Here is the code to get value from SharedPreference.
SharedPreferences sharedpreferences=getApplicationContext().getSharedPreferences("user", Activity.MODE_PRIVATE);
int ans = sharedpreferences.getInt("ans1",7);
Value of ans always is 7.

Overwriting a previous highscore using sharedpreferences

I've managed to get my score to save to SharedPreferences correctly as well as it saving to highscore. However when checking if the previous score is better than the saved highscore, it always saves over it no matter what and I don't know why.
// save score and time if current score is > than current highscore and time is > than current hightime
if (score > scorePreferences.getInt("highscore", 0) && time > timePreferences.getInt("hightime", 0)) {
highscorePreferences = getContext().getSharedPreferences("highscore", 0);
SharedPreferences.Editor editorHighscore = highscorePreferences.edit();
editorHighscore.putInt("highscore", score);
editorHighscore.commit();
timePreferences = getContext().getSharedPreferences("hightime", 0);
SharedPreferences.Editor editorHightime = timePreferences.edit();
editorHightime.putInt("hightime", time);
editorHightime.commit();
}
It then gets read in gameoveractivity and highscore activity using this code:
// load score from last session
private void load() {
// get score and set text field
scorePreferences = getSharedPreferences("score", 0);
score = scorePreferences.getInt("score", 0);
scoreValue.setText(Integer.toString(score));
// get time and set text field
timePreferences = getSharedPreferences("time", 0);
time = timePreferences.getInt("time", 0);
timeValue.setText(Integer.toString(time) + " seconds");
// get highscore and set text field
highscorePreferences = getSharedPreferences("highscore", 0);
highscore = highscorePreferences.getInt("highscore", 0);
highscoreValue.setText(Integer.toString(highscore));
}
Should this:
if (score > scorePreferences.getInt("highscore", 0)...
...not be something like:
if (score > highscorePreferences.getInt("highscore", 0)...
The key "highscore" is in your preferences set with that same name. It looks like you are reading that key from the "score" preferences instead. It's not there, so the default of 0 is always being used.
It looks like you use same key for your sharedpreferences that is why the values override.
I would recommend using sqlite for storing top scores.
Use one SharedPreferences object. To save, you can do this:
SharedPreferences prefs = getSharedPreferences("score", Context.MODE_PRIVATE);
int highscore = prefs.getInt("highscore", 0);
int hightime = prefs.getInt("hightime", 0);
if (score > highscore && time > hightime) {
SharedPreferences.Editor editor = prefs.editor();
editor.putInt("highscore", score);
editor.putInt("hightime", time);
editor.commit();
}
Then load it, also use one SharedPreferences object:
private void load() {
SharedPreferences prefs = getSharedPreferences("score", Context.MODE_PRIVATE);
score = prefs.getInt("score", 0);
scoreValue.setText(Integer.toString(score));
time = prefs.getInt("time", 0);
timeValue.setText(Integer.toString(time) + " seconds");
highscore = prefs.getInt("highscore", 0);
highscoreValue.setText(Integer.toString(highscore));
}
NOTES:
it's a good idea to use keys for prefs file name and variables, so that you can avoid easy typo mistakes when saving/retrieving variables, eg.
public static final String PREFS_NAME = "score";
public static final String KEY_HIGHSCORE = "highscore";
public static final String KEY_HIGHTIME = "hightime";
then use it
SharedPreferences prefs = getSharedPreferences(ClassNameWhereItsDeclared.PREFS_NAME, Context.MODE_PRIVATE);
editor.putInt(ClassNameWhereItsDeclared.KEY_HIGHSCORE, score);
etc.
I don't see where you're saving time and score, but you can do it the same way as highscore and hightime

problem While Sharing text in Android using SharedPreferences

I am Following this link to use the SharedPreferences.Am trying to Apply in my Application but The Shared value returns the null value
Here my code To assign the Shared Variable
SharedPreferences sharedPreferences = getSharedPreferences("pref",Activity.MODE_WORLD_READABLE);
SharedPreferences.Editor editor= sharedPreferences.edit();
String l="hello";
editor.putString(l,"imagepath");
editor.commit();
here code to access the Shared variable
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString("imagepath",null);
Toast.makeText(getBaseContext(),"create banner"+prefName,Toast.LENGTH_LONG).show();
here prefName returns null value.It Cannot Shared.
The preference name is "hello", not "imagepath".
String prefName = myPrefs.getString("hello", null);
And I think it's better to use getString("hello", ""). This way, prefName will never be null.
You have written "myPrefs" in (SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);)
Change it like this (SharedPreferences myPrefs = this.getSharedPreferences("pref", MODE_WORLD_READABLE);)
here i have change "myPrefs" in ("myPrefs", MODE_WORLD_READABLE) to "pref" .
Now you the coorect one be ("pref", MODE_WORLD_READABLE)
you are using wrong key.
get string like this:
String prefName = myPrefs.getString("hello",null);
you are also using two different sharedPreference name:
SharedPreferences sharedPreferences = getSharedPreferences("pref",Activity.MODE_WORLD_READABLE);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
Please make sure you write and read in same SharedPreference.
Your code to write in SharedPreference should look like this:
SharedPreferences sharedPreferences = getSharedPreferences("pref",0);
SharedPreferences.Editor edito r= sharedPreferences.edit();
String l="hello";
editor.putString(l,"imagepath");
editor.commit();
To read from SharedPreference should look like this:
SharedPreferences myPrefs = this.getSharedPreferences("pref", 0);
String prefName = myPrefs.getString("hello",null);
Toast.makeText(getBaseContext(),"create banner"+prefName,Toast.LENGTH_LONG).show();
Switch this around:
editor.putString("imagepath", l);
also you will want to change the possible return value of "null" to a more acceptable error return value, maybe 0 or -1.
String prefName = myPrefs.getString("imagepath","0");
Source Android Doc for Editor:
abstract SharedPreferences.Editor putString(String key, String value)
//Set a String value in the preferences editor, to be written back once commit() or apply() are called.

Categories

Resources