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

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.

Related

unable to clear my sharedPreferences using editor.clear().commit();

I am working on an android project where I have a scenario such as :
I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.
but the problem is when I closed activity and again open that activity; my data still visible in TextView.
even when I cleared it in onDestroy().
here is my code for send data :
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("address", (String) Address);
editor.commit();
finish();
here is my code to set and clear data:
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
String n = settings.getString("name", "");
String a = settings.getString("address", "");
name.setText(n);
location.setText(a);
}
#Override
protected void onDestroy() {
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
here is my preference manager class :
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "sara";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.clear().commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.
I'm not sure where you are using SharedPreference object to set data in it. But I guess this is the problem:
In this activity, you are clearing SharedPreferenece correctly.
You go back to previous Activity. And the previous activity, sets data to shared preference, again. So SharedPreference is not empty anymore.
You go to second activity (which you remove shared preference data in onDestroy()). As shared preference is not empty, you are seeing data again.
So check the code again and feel free to ask any questions.
Try check the logs to make sure you are really going 'onDestory' well.
#Override
protected void onDestroy() {
Log.d("address", "onDestory");
SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("address");
editor.clear().commit();
super.onDestroy();
}
There is no problem with the code for creating and removing SharedPreferences.

Can SharedPreferences be not saving?

I have one application that uses SharedPreferences to record the checkin or checkout state of the user.
If the checkin is pressed, it's button is grayed out the checkout becomes available, the opposite work as well.
However some users tells me that "sometimes" they will make another checkin on the next day and the checkout is still available.
Im supecting that they are forgetting to tap it, but i want to know if is there by any chance that this SharedPreferencces get cleared by itself?
this is the part of my code that i save the checkin state:
SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("statuscheckin", 1); //1 for checkin, 0 for checkout
editor.commit();
this is the part where i check it
if (getSharedPreferences("MyPreferences", Context.MODE_PRIVATE).getInt("statuscheckin", 0) == 1) {...}
Unless you clear the storage/cache, SharedPreferences won't get cleared by itself.
Make sure you are not clearing it by yourself for any condition happening.
If you are getting the default value only, it's possible that you are using it before the value gets committed.
Try this code,
Session Manager code:
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
public static final String KEY_CHECKIN= "checkin";
public void setCheckin(boolean login){
editor = sharedPreferences.edit();
editor.putBoolean(KEY_CHECKIN,checkin);
editor.apply();
}
public boolean getCheckin(){
return sharedPreferences.getBoolean(KEY_CHECKIN,false);
}
In your Java code:
SessionManager sessionmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionmanager = new SessionManager(this);
//Condition for checkin
if(user checkedIn){
sessionmanager.setCheckin(true);}
//Retrieving the value when user again opens the app:
if(sessionmanager.getCheckin()){}////proceed with your logic.

Save/Load problems with SharedPreferences in Android

and sorry if this is a stupid question. I'm learning to use SharedPreferences and I have a bit of a problem:
I'm using this code to save to SharedPreferences:
public void saveInMemory(String[] saveThis){
StringBuilder sb = new StringBuilder();
prefs = PreferenceManager.getDefaultSharedPreferences(OIBListActivity.this);
editor = prefs.edit();
for (int i = 0; i < saveThis.length; i++) {
sb.append(saveThis[i]);
sb.append(";");
}
editor.putString("listaOIB", sb.toString());
editor.commit();
}
And this code to load saved values:
public String loadFromMemory(String id){
prefs = PreferenceManager.getDefaultSharedPreferences(OIBListActivity.this);
return prefs.getString(id, "NOPREFSAVED");
}
I've also already declared prefs and editor outside, so that shouldnt be a problem:
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
Now, my problem is that when I enter this activity and save files that i received from other activity(via putExtra, if that helps), then proceed to load it everything works fine.
Then I reenter my activity without sending any files to it (from other activity) and try to use loadFromMemory() and it doesnt work. My understanding is that it should have saved files when I entered Activity for the first time, and then load it whenever I want.
Any help?
add the method and call when you add and other is call when you get
//this method is call when you add the data
public static void setAlarmHourTime(String value, Activity activity) {
SharedPreferences.Editor pref = activity.getSharedPreferences("ALARMHOURTIME", Context.MODE_PRIVATE).edit();
pref.putString("alarmhourtime", value);
pref.commit();
}
//this method is call when you retrive the data
public static String getAlarmHourTime(Activity activity) {
SharedPreferences prefs = activity.getSharedPreferences("ALARMHOURTIME", Context.MODE_PRIVATE);
return prefs.getString("alarmhourtime","7");
}
if you want to retrieve content saved in editor.putString("listaOIB", sb.toString());, then the id you pass in loadFromMemory should be "listaOIB".
Is it the case?

How do I set up a global variable to share among views in Android?

In one of my views the user makes a selection. I want to store that selection in a variable I can use across all views so it can be used for further database queries such as "bookId".
How can I make "bookId" a global variable that is set on one view and can be accessed across the other views when needed?
----- Edit: What I'm attempting to do based on comments and answers -----
On my main activity where the SharedPreference is stored I have this before the onCreate:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Integer bookId;
In my onCreate I've done this:
settings = getSharedPreferences(PREFS_NAME, 0);
bookId = settings.getInt("bookId", 0);
After the button press I'm storing a custom attribute and attempting to set bookId in the SharedPreference:
SharedPreferences.Editor editor = settings.edit();
editor.putInt("bookId",bookKey);
editor.commit();
In another view I'm attempting to get the bookId from the SharedPreference and, for testing purposes, I'm trying to set the stored value to a textView just to make sure it stored and carried over correctly.
Before the onCreate on the second view:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Inside the onCreate:
settings = getSharedPreferences(PREFS_NAME, 0);
Integer bookId = settings.getInt("bookId", (Integer) null);
tempBookTextView = (TextView) findViewById(R.id.tempBookTextView);
tempBookTextView.setText(bookId);
I have a two questions, how does this look so far? Any ideas why the app crashes when I use
Integer bookId = settings.getInt("bookId", (Integer) null);
Instead of using global variable to access variable value through out the app try using SharedPreferences.
sample activity:
public class Book extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
String mBookId = null;
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
mBookId = settings.getString("book_id", null);
// use book_id;
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("book_id", mBookId);
// Commit the edits!
editor.commit();
}
}
Preferences are typically created private and can be accessed via all over the application components. Sharing data with other application with world readable or writable preference file is rarely used, as the external component would need to know the exact filename and location of the file.
To kill the spirit of encapsulation,
public class Globals {
public static int x;
public static int y;
}
and later
if (Globals.x == 0) { ... }
But please don't do exactly that, any class can contain static variables, find a class responsible for the value you want to store.
OTOH, android processes may be restarted when you don't expect it, in which case all the variables will be reset. So it's better to use shared preferences and if they don't work as expected (which I have seen in at least one release of Android), store the instance of shared preferences in a static variable.
You can use Shared Preferences
Saved at once !
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ProjectAct.this).edit();
editor.putInteger(StaticVariable.BOOKID, "1");
p.get("contract_no"));
editor.commit();
Then call from anywhere like that
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int book_id = prefs.getInteger(StaticVariable.BOOKID,null);
See more at How to use SharedPreferences in Android to store, fetch and edit values

sharedpreferences that don't change from activity to activity?

If i set a sharedpreference in one activity, why does the other one has different preferences? context changed? (but i se use application context!)
Here is my code
MyApp appState = ((MyApp)this.activity.getApplicationContext());
appState.setDittaSelezionata( (int) itemId);
....
MyApp appState = ((MyApp)this.getApplicationContext());
int ditta_id_selezionata = appState.getIdSomething();
And
public class MyApp extends Application implements Parcelable {
private SharedPreferences getSharedPrefs()
{
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//SharedPreferences settings = this.getSharedPreferences(MyApp.PREFS_NAME, this.MODE_PRIVATE);
return settings;
}
public int getIdSomething() {
SharedPreferences settings = this.getSharedPrefs();
return settings.getInt("ditta_id_selezionata", 0);
}
public void setDittaSelezionata(final int ditta_selezionata) {
SharedPreferences settings = this.getSharedPrefs();
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ditta_id_selezionata", ditta_selezionata);
// Commit the edits!
editor.commit();
}
...
How can i make global preferences that are shared among all activities android 3.2? is there something android provides or i have to code a save to file/open to file and add it for each activity onStop() / onCreate() ?
try this.
private static final String APP_PREF = "application_preference";
private static final String DITTA = "ditta_id_selezionata";
public class MyApp extends Application implements Parcelable {
private SharedPreferences getSharedPrefs(){
SharedPreferences settings = getApplicationConext().getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return settings;
}
public int getIdSomething() {
SharedPreferences settings = this.getSharedPrefs();
return settings.getInt(DITTA, 0);
}
public void setDittaSelezionata(final int ditta_selezionata) {
SharedPreferences settings = this.getSharedPrefs();
SharedPreferences.Editor editor = settings.edit();
editor.putInt(DITTA, ditta_selezionata);
// Commit the edits!
editor.commit();
}
I think you had done something similar but commented it. This should keep your preferences constant throughout the app over the activities. As you see here, you make sure that the same preference file is being read and written to.
Shared Preferences ARE persisted across activities. If you're seeing different data then I expect the values are not being saved. I don't think the issue is the reading of the data, but the writing, so check your preference writing code.

Categories

Resources