SharedPreferences doesn't save value - android

I have this code:
public class Register extends Activity {
private LinearLayout layout;
private TextView debug;
public static final String USER_CONFIG = "UserConfigs";
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
SharedPreferences settings = getSharedPreferences(USER_CONFIG, MODE_PRIVATE);
boolean registered = settings.getBoolean("registered", false);
layout = (LinearLayout) findViewById(R.id.layoutRegister);
if (!registered) {
debug = new TextView(this);
debug.setText("You have to register");
layout.addView (debug);
//TO DO user registration
settings.edit().putBoolean("registered", true);
settings.edit().commit();
} else {
debug = new TextView(this);
debug.setText("You have already registered");
layout.addView (debug);
//TO DO skip to next screen
}
}
}
But I'm always getting registered as "false" when I restart my app. I have tried to commit it on the onStop() as well and got the same result. I have seen other topics with this problem here but none of them had the same problem as I do.
Any ideas?

You can't do this:
settings.edit().putBoolean("registered", true);
settings.edit().commit();
You need to get the editor object, then make the changes:
Editor editor = settings.edit();
editor.putBoolean(...);
editor.commit();

SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
Editor edit = prefs.edit();
edit.putBoolean("registered", true);
edit.commit();
use this

The other answers are also correct.
You can also use this
settings.edit().putBoolean("registered", true).commit();

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.

Saving data on android APP

Hello I'm working on app android which notices the scores of a card's game.
I'm looking for how to save the actual scores and teams' name when the app getting destroyed or stopped to find them when i open it again.
public class ShowScore extends AppCompatActivity {
SharedPreferences save = null;
private TextView nameTeam1= null;
private TextView nameTeam2= null;
private TextView scoreTeam1 = null;
private TextView scoreTeam2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_score);
nameTeam1= (TextView) findViewById(R.id.team1);
nameTeam2= (TextView) findViewById(R.id.team2);
scoreTeam1 = (TextView) findViewById(R.id.score1);
scoreTeam2 = (TextView) findViewById(R.id.score2);
nameTeam1.setText(save.getString("Team1","Team 1"));
nameTeam2.setText(save.getString("Team2","Team 2"));
scoreTeam1.setText(String.valueOf(save.getInt("Score1", 0)));
scoreTeam2.setText(String.valueOf(save.getInt("Score2", 0)));
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
save = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = save.edit();
editor.putString("Team1", nameTeam1.getText().toString());
editor.putString("Team2", nameTeam2.getText().toString());
editor.putInt("Score1", Integer.parseInt(scoreTeam1.getText().toString()));
editor.putInt("Score2", Integer.parseInt(scoreTeam2.getText().toString()));
editor.commit();
}
}
EDIT It is fixed i should add
save = getApplicationContext().getSharedPreferences("MyPref", 0);
Into the onCreate().
Recently i started investing in sqlite database, just purely because it stays on the system, and is further exportable. but a great tutorial i followed was
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
This has all the C.R.U.D for database application.
You can try many options if data is small and just variables then you can try shared preferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
just like that and value will be stored
and for retriving data then you need just
pref.getString("key_name", null); // getting String

Android: issue with data storage (SharedPreferences)

I'm learning android and for this project I need to save user's data - color change of buttons, in this case -. During the program the change occurs (onClick), but when I restart the app, nothing happens - the change has not been saved (or read...) Can someone help me? Code:
final String paintKey = "paint";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCreate();
preferences();
togglePlay();
}
public void preferences(){ //the issue in this method?
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
settings.getBoolean(paintKey,false);
String backGround = settings.getString("stage", "Indoors");
if (backGround.equals("Indoors")) {
Picasso.with(this).load(R.drawable.shocked_crowd).fit().centerCrop().into(stage);
}
if (backGround.equals("Street")) {
Picasso.with(this).load(R.drawable.coins).fit().centerCrop().into(stage);
}
}
public void changeColor(){
if(!paint) { //paint variable has global scope and it is set to false
c1.setBackgroundColor(Color.YELLOW);
paint = true;
}else{
c1.setBackgroundColor(Color.BLUE);
paint = false;
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("paint", paint);
editor.commit();
}
EDIT: the onClick method:
public void onClick(View v) {
if(v==color){
changeColor();
}
EDIT: this is how I have it now:
public void preferences(){
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
final String paintKey = "paint";
settings.getBoolean(paintKey,false);
Wrong? if I put editor instead of settings i get red underlined
In order to work with SharedPreferences you need a global key
final String paintKey = "paint"
To write boolean value info SharedPreferences use
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(paintKey, paint).commit();
To read that data later
paint = settings.getBoolean(paintKey, false);
settings.getBoolean(paintKey,false);
This line gets a value from the SharedPreferences and promptly ignores it. You must save the return value in a variable in order to use it later:
boolean paint = settings.getBoolean(paintKey,false);
This will create a local variable that can only be used in the same method. If you need to use the value in other methods, create a field instead.

Save User Data using SharedPreferences

I am writing an app to save password with a login interface. The user can change the login password. First time, I use the following code to save the password, so that the password will not reset when the app relaunch:
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putString("pwd", currentPwd);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState){
currentPwd = savedInstanceState.getString("pwd");
}
But after I asked that, someone in this website suggested me to use "SharedPreferences". So, I changed the code as follow:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
SharedPreferences settings = getSharedPreferences("setting", 0);
currentPwd = settings.getString("pwd", "abc");
}
#Override public void onStop(){
super.onStop();
SharedPreferences settings = getSharedPreferences("setting", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("pwd", currentPwd);
editor.commit();
}
After my experiment, I found that the password will be reset after one hour which the same as the first code. Have I changed it wrong for the second code? Or there are any suggested way to solve it? Thank you.
Not sure I'm following your code, but here is how I would do this:
To get password:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.getString("pwd", "abc");
To set password:
SharedPreferences.Editor editor = sp.edit();
editor.putString("pwd", currentPwd);
editor.commit();
Hope that helps
You can save value using bellow function.It contains only context, key and the value:
public void savePreferencesForReasonCode(Context context,
String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
To get more see this Answer

How to save the state of the toogleButton on/off selection?

Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection that is "off".
So can any budy tell mw what should i have to save the state of the toogleButton selection and perform some action based on that toggleButton selection state. . .
Thanks.
Use SharedPreferences.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if((tg.isChecked()))
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.commit();
}
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
tg.setChecked(true);
}
else
{
tg.setChecked(false);
}
I did not verify this code, but look at some examples on the net, it is easy!
Use SharedPreferences like erdomester suggested, but I modified little bit his code. There's some unneeded conditions.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", tg.isChecked()); // value to store
editor.commit();
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
tg.setChecked(tgpref);
The best way, you can set tgbutton same
screen main
Intent intent = new Intent(this, Something.class);
intent.putExtra(BOOLEAN_VALUE, Boolean.valueOf((tvConfigBoolean.getText().toString())));
startActivity(intent);
screen something
Bundle bundle = getIntent().getExtras();
tbtConfigBoolean.setChecked((bundle
.getBoolean(MainActivity.BOOLEAN_VALUE)));
and save state
editor.putBoolean("BooleanKey", tbtConfigBoolean.isChecked());
editor.commit();
good luck

Categories

Resources