SharedPreferences not working as expected, cannot read nor write preferences - java

private void init() {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
// SET VALUE RECORD
record = prefs.getInt("record", 0);
prefs.edit().commit();
}
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
if(i > prefs.getInt("record", 0))
prefs.edit().putInt("record", i);
prefs.edit().commit();
}
private int getRecord() {
int rec;
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
rec = prefs.getInt("record", 0);
prefs.edit().commit();
Toast toast = Toast.makeText(this, rec+"", Toast.LENGTH_SHORT);
toast.show();
return rec;
}
this code should set an int and retrieve it, but it doesn't seem to ever set it... can you see why is that?

Think it is best to call the interface SharedPreferences.Editor to edit preferences instead of using prefs.edit().putInt("record", i);. The docs say...
Modifications to the preferences must go through an
SharedPreferences.Editor object to ensure the preference values remain
in a consistent state and control when they are committed to storage.
If you change your setMethod to the following it should work...
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if(i > prefs.getInt("record", 0))
editor.putInt("record", i);
editor.commit();
}
And I guess you are calling the above method setRecord somewhere in your code as I can't see it being called anywhere in the code snippet you pasted.

try
Editor editor = prefs.edit();
editor.putInt("record",i);
editor.commit();

Related

Sharedpreferences android studio error saving data [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I saved my data from an numberDecimal edit text using sharedpreference. When I want to get that data in another activity, it always appears as null, so it wasn't saved correctly. Any suggestion?
This is my code from where I save the data :
public void Start(View view) {
EditText LevelEdit = (EditText) findViewById(R.id.editText_LevelCurrent);
String User_Level = LevelEdit.getText().toString();
if (User_Level == "") {
Toast.makeText(this, "Select a level",
Toast.LENGTH_LONG).show();
} else {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(GameConstants.StringvalueOfLevel,User_Level);
editor.commit();
Intent myIntent = new Intent(Mygame_Menu.this, Mygame.class);
startActivity(myIntent);
}
}
i think your condition is wrong and because of that your saving null object in shared preference don't check the string like this if (User_Level == "")the == operator dose not work on the strings in java ! you should use equals method for comparing to String like this "Amir".equals("Amir")
use this instead if (User_Level==null||User_Level.isEmpty())
You are missing to put sharedPreference name as parameter causes error.
Instead of this
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
Change
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("sharedPreferenceName",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
You can't compare string value with int format in if loop. Change
if(User_Level == "")
To
if(User_Level.equals(""))
So it will check the condition as correct. Otherwise above will execute else part even if its null.
EDITED
private static final String PREFS_NAME = "PREF_LEVEL_DATA";
private static final String PREFS_KEY = "LEVEL";
public void SaveLevel(Context context, String level) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREFS_KEY, level);
editor.commit();
}
public String RetrieveLevel(Context context) {
String level;
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(PREFS_KEY)) {
level = settings.getString(PREFS_KEY, "");
} else {
return "";
}
return level;
}
For store a value
SaveLevel(getApplicationContext(), User_Level);
For retreive a value
String level = RetreiveLevel(getApplicationContext());
UPDATED
EditText LevelEdit = (EditText) findViewById(R.id.editText_LevelCurrent);
String User_Level = LevelEdit.getText().toString();
if (User_Level.equals("")) {
Toast.makeText(this, "Select a level",
Toast.LENGTH_LONG).show();
} else {
SharedPreferences sharedPref = getSharedPreferences("ANY_PREFERENCE_NAME",
Context.MODE_PRIVATE); //Replace "ANY_PREFERENCE_NAME" as your own string
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(GameConstants.StringvalueOfLevel,User_Level);
editor.commit();
Intent myIntent = new Intent(Mygame_Menu.this, Mygame.class);
startActivity(myIntent);
}

Android - SharedPreferences aren't saving when I restart the app

I'm using Android Studio to make a game, and my SharedPreferences which I'm using for a highscore aren't being saved when I reload the app. Within the app it works fine, but restarting sends the highscore back to the default value (0).
Setting my SharedPreferences in MainActivity:
SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if(currentTopic == 4){
if(settings.getInt("HIGHSCORE", 0) < Math.round(scoreTotal)){
editor.clear();
editor.putInt("HIGHSCORE", Math.round(scoreTotal));
editor.apply();
editor.commit();
}
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
homeIntent.putExtra("Score", Integer.toString(Math.round(scoreTotal)));
startActivity(homeIntent);
editor.commit();
finish();
To clarify, the code does make it into the if statement. "scoreTotal" is the highscore which I am saving.
Getting my SharedPreferences in HomeActivity:
SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highscore = settings.getInt("HIGHSCORE", 0);
Log.i("highscore", String.valueOf(highscore));
TextView tv_highscore = findViewById(R.id.tv_highscore);
tv_highscore.setText("Highscore: "+String.valueOf(highscore));
Where have I gone wrong?
Please let me know if I have forgotten to include something. I've tried many things from previous StackOverflow posts but to no avail. Thanks in advance.
EDIT: To clarify, my problem came from not being able to do SharedPreferences in that activity then get them from another. I used the intent extra message and did all the SharedPreferences in the HomeActivity and it worked. Hope this is able to help some people.
Try this instead:
SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
long score = Math.round(scoreTotal);
if(currentTopic == 4){
if(settings.getInt("HIGHSCORE", 0) < score){
editor.putInt("HIGHSCORE", score);
editor.apply();
}
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
homeIntent.putExtra("Score", Integer.toString(score));
startActivity(homeIntent);
finish();
I suspect that you do not need (or even really want) to call editor.clear(); since this (according the the Google Docs) will
Mark in the editor to remove all values from the preferences
.
And there is no need to call apply and commit one will do:
Google Docs:
Unlike commit(), which writes its preferences out to persistent
storage synchronously, apply() commits its changes to the in-memory
SharedPreferences immediately but starts an asynchronous commit to
disk and you won't be notified of any failures. If another editor on
this SharedPreferences does a regular commit() while a apply() is
still outstanding, the commit() will block until all async commits are
completed as well as the commit itself.
You can make a class for saving data like this
public class GameData {
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private Context context;
private int PRIVATE_MODE = 0;
private static final String PREF_NAME = "GAME_DATA";
public GameData(Context context){
this.context = context;
preferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = preferences.edit();
}
public void set(String key, boolean value){
editor.putBoolean(key, value);
editor.commit();
}
public void set(String key, String value){
editor.putString(key, value);
editor.commit();
}
public void set(String key, long value){
editor.putLong(key, value);
editor.commit();
}
public void set(String key, int value){
editor.putInt(key, value);
editor.commit();
}
public void set(String key, float value){
editor.putFloat(key, value);
editor.commit();
}
public float get(String key, float defaultValue){
return preferences.getFloat(key, defaultValue);
}
public int get(String key, int defaultValue){
return preferences.getInt(key, defaultValue);
}
public long get(String key, long defaultValue){
return preferences.getLong(key, defaultValue);
}
public String get(String key, String defaultValue){
return preferences.getString(key, defaultValue);
}
public boolean get(String key, boolean defaultValue){
return preferences.getBoolean(key, defaultValue);
}
}
Then call the class to set/get your data
private GameData gamedata;
gamedata = new GameData(getApplicationContext());
gamedata.set("HIGHSCORE",score); // FOR SET THE HIGHSCORE
int highscore = gamedata.get("HIGHSCORE", 0); // FOR GET THE HIGHSCORE

sharedPreferences.getString() return null

Im trying to display the user email in a textView using SharedPreferences.
Shared preferences is created in loginActivity.
I try to access it from mainActivity.
My session using sharedPreference work well (with a login boolean saved in sharedPreferences files).
So what's wrong?
- A context error?
- Because I try to access the data from an another activity?
Please help :) Thanks a lot!
Here is the code im using :
Login Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
...
//Creating a shared preference in a login()
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
...
Main Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
email_session = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Private");
usernameText.setText(email_session);
}
to read the stored preferences you need to do:
to save
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();
to read it
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);
This happens because your value is not stored in the shared preferences.
SharedPreferences pref = getSharedPreferences("your Pref Name", 0) // 0 for Private Mode
String name = pref.getString("your key store when login", null); // null is the default value you can put it here "No value". then you will not get null pointer.

Can't read SharedPreferences

I'm storing some values in my PreferencesFragment in this way:
// SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = getPreferenceScreen().getSharedPreferences();
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
Then, I want to read the preferences in a non activity class:
// SharedPreferences prefs = ActivityHandler.getCurrentActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = ActivityHandler.getCurrentActivity().getPreferences(0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
I've tried also the uncommented code, but I get always 0 for both values.
Try this
Store with SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("my_pref", Context.MODE_MULTI_PROCESS);
Editor editor = sharedPref.edit();
editor.putInt("KEY", VAL);
..
..
editor.commit();
Retrieve from SharedPreferences
SharedPreferences sharedPref = getSharedPreferences(
"my_pref", Context.MODE_MULTI_PROCESS);
int size = sharedPref.getInt("KEY", default_VAL);
This will be helpful...thanks
You are doing it wrong. Each time you are getting a different shared preference. Use this code:
For storing value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
For fetching value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
Hope this will help you.

SharedPreferences Login

I'm trying to create something that needs to get information in the first time and save it. The app starts at the MainActivity, if it does not have the information needed, the app send you to the MotoActivity. Once the app has the information you don't need to go to the MotoActivity anymore. I know i'm wrong but I don't know how to do.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("valid", 0);
editor.commit();
int n = sp.getInt("valid", -1);
if(n == 0){
editor.putInt("valid", 1);
editor.commit();
startActivity(new Intent(MainActivity.this, MotoActivity.class));
MainActivity.this.finish();
}
First check for the very first time that, if "userLoggedBefore" is true or false from the SharedPreferences, if the user had used the application before and had entered the right credentials, we will save authenticated to true and if he hasn't we will set the default value as false.
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
boolean authenticated = sharedPref.getBoolean("userLoggedBefore", false);
then check -
if (authenticated){
//show your MainActivity
} else {
// show your MotoActivity
}
in your MotoActivity,
//if credentials matches
if(credentialMatches)
SharedPreferences sharedPref = getSharedPreferences(
"Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", true);
prefEditor.commit();
else{ // if credentials doesn't match
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", false);
prefEditor.commit();
}
Try this:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// app already has the needed info.
if(sp.getInt("valid", -1) == 1){
// do something
}
// app needs info. first, when you have got the info. in MotoActivity then set preferences key 'valid' to 1
else{
startActivity(new Intent(MainActivity.this, MotoActivity.class));
finish();
}

Categories

Resources