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}
}
Related
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.
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.
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.
How to show a dialog in android on navigating to another activity only for the first time? I dont want to put it in the onResume() of the activity because then the dialog shows up each and every time i navigate to that activity.
Use this finction in onCreate handler
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (isFirstTime()) {
// show dialog
}
...
}
/***
* Checks that application runs first time and write flag at SharedPreferences
* #return true if 1st time
*/
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
I am making an activity that will edit the shared preferences just when the activity starts before it executes any functions. I am stuck and dont know how to. My app only edits the shared preferences when i close the app or go back to another activity. I want to edit them when the activity starts without executing any function ie checkpreferences();.Precisely How to edit the shared preferences on start of activity?
public class MyActivity extends Activity {
private SharedPreferences app_preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
final int id = 42;
int idd = app_preferences.getInt("idd", 0);
// I am Stuck in this part
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("idd", 43);
editor.commit(); // Very important
final int iddd = idd;
checkpreferences(id, iddd);
}
private void checkpreferences(int di, int dii) {
if(di == dii) {
Toast.makeText(AudioActivity.this,"id is same"+dii+"="+di , Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AudioActivity.this,"id is different"+dii+"!="+di, Toast.LENGTH_SHORT).show();
}
}
}
I think the error is here
you are tryinh to fetvh the value of shared preference before saving it
// Fetching of value
int idd = app_preferences.getInt("idd", 0);
Log.e("value " , " is " + idd);
as at this time there shall be no value in preference
// and commitng after it
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("idd", 43);
editor.commit(); // Very important
you should save preference before fetching
and to assure it print the logs as well