Can SharedPreferences be not saving? - android

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.

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.

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.

android using shared preferences issue

static int existingCounter;
Context mContext = SplashScreen.getContextOfApplication();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
public static int cCounter()
{
MainMenu mm = new MainMenu();
existingCounter = mm.getExistingCounter();;
return existingCounter;
}
public void setSharedPreferences(int count)
{
SharedPreferences preferences = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("existingCount", existingCounter);
editor.commit();
}
//Get value from shared preferences
public int getExistingCounter()
{
SharedPreferences myPrefs = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
myPrefs.getInt("existingCount", 0);
return existingCounter ;
}
Hi all, above is my shared preferences. What I am trying to achieve is when user 1st launch the app, my app shall direct user to the disclaimer page and after the user agree to the T&C then in future the user launch the app shall not show the disclaimer page again. However, my current codes only valid when user never exit app. If the user were to exit the app and relaunch, my app still shows the disclaimer page. Please assist =) Thank you in advance. Below is the part where I set the sharedpreferences:
case 3:
cCounter();
if(existingCounter==0)
{
changeMenuFrag(new AcknowledgePg());
existingCounter++;
setSharedPreferences(existingCounter);
}
else
{
changeMenuFrag(new GalleryMain());
}
break;
Save a flag in the Preferences when you start up the application, after you've done the welcome screen stuff. Check for this flag before you show the T&C screen. If the flag is present (in other words, if it's not the first time), don't show it. Instead of a integer counter use a boolean flag and in your main activity check if the flag is true or false based on that show the appropriate activity.
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference}
}

How to write encrypted app data and decrypte it

I want to store my app data in a file so it could be accessed every time from the app - for example: money, user score, user current sprite...
I have never seen encryption in my life, and I wanted to know if there is an easy way to encrypt data and write it to the phone, and then decrypt it next time the app is open.
If there is no easy way, it would be great if someone could explain how the encryption/decryption works to me.
Use SharedPreferences.
I've used them, and you dont need to encrypt the data.
http://developer.android.com/guide/topics/data/data-storage.html#pref
EXAMPLE(from developer.android):
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#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.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}

How to skip an activity? android

i have a default activity that starts first (Activity A), and from there the user can go to another activity (Activity B). In B after some work the user sets a sharedpreference. the next time the app starts i want to check in A if sharedpreference is null to go to B. and i put this if just under
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
and it encapsulates the whole onCreate. when the app starts it skips A and on B i shows the layout and the FC with NullPointerException.
Any one got experience with this?
OR
any one got a better idea on skipping A?
Well Simon you have to use Shared prefrences. save your data in shared prefrences. Then in the activity where you want to use the data in Shared prefres again get instance of same shared prefrence. get the data and use it.
go through this code
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#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.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
probably you will get an insight
To answer my own question. i had a location listener in onDestroy an because it was not initialized because of skipping onCreate it returned NullPointer.

Categories

Resources