This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
Closed 4 years ago.
How can I use SharedPreferences on Android Studio to save some data like the value of a boolean?
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
editor.putBoolean("firststart",false);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);
boolean firstStart= prefs.getBoolean("firststart",false);
if (!firstStart) {
Intent intent12 = new Intent(getApplicationContext(),FirstStart.class);
startActivity(intent12);
prefs.getBoolean("firststart",true);
}
else if (firstStart) {
}
If I use this code everytime I create the activity the value of the boolean return false and then true.
How can I resolve this problem and don't lose the data?
You do not need to save false as value everytime , simply if there is no value, you get false here prefs.getBoolean("firststart",false) otherwise true as your saved value
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);
boolean firstStart= prefs.getBoolean("firststart",false);
if (!firstStart) {
// save true during first time initialization
Intent intent12 = new Intent(getApplicationContext(),FirstStart.class);
startActivity(intent12);
editor.putBoolean("firststart",true);
editor.apply();
} // for second run, when you get true
else if (firstStart) {
}
well actually your code is resetting itself on each onCreate so what you have to do is something like this
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firststart", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firststart", false).commit();
}
}
}
hope this helps
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 have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}
Android issue with boolean on shared preferences
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSlide=spref.getBoolean("SLIDE_SHOW",false);
//in isSlide am getting the right value but the if statement is not working
if(isSlide==true){
//if true the page will slide but it works in false too
}
i tried in this link Issue with boolean on shared preferences but the answer is not clear
settings code:
<PreferenceCategory android:title="Slide Show" >
<CheckBoxPreference android:title="Slide Show" android:key="SLIDE_SHOW" />
</PreferenceCategory>
You may want to check if your SharedPreference variables are active. This is an example on how to set the SharedPreference.
To write into SharedPreference:
SharedPreferences prefs = getSharedPreferences("myPref", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("myBool", true);
editor.commit();
To read from SharedPreference:
SharedPreferences prefs = getSharedPreferences("myPref", 0);
if (prefs.getBoolean("myBool", false)) { //myBool is true; }
sorry i will not post the question correctly
The problem is not with preference it returns correct value the problem is in handler which is used to slide the viewpager based on the value which is returned by preference
the handler is running even though the activity is killed below the code solved my problem
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSlide=spref.getBoolean("SLIDE_SHOW",false);
if(isSlide==true)
{
SlideShowTimer();
}
public void SlideShowTimer()
{
mFilterTask = new Runnable() {
#Override
public void run() {
int i=0;
itemPosition = viewPager.getCurrentItem() + 1;
if(itemPosition!=10)
{
if(i <= adapter.getCount()-1)
{
viewPager.setCurrentItem(itemPosition,true);
mHandler.postDelayed(mFilterTask, 3000);
i++;
}
}
else
{
//ViewPagerAdapter.mediaPlayer.stop();
ViewPagerActivity.this.finish();
}
}
};
mHandler.removeCallbacks(mFilterTask);
mHandler.postDelayed(mFilterTask,3000);
}
#Override
public void onDestroy(){
super.onDestroy();
mHandler.removeCallbacks(mFilterTask);
}
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}
}
I move from Activity A to Activity B by intent.I am storing some values in shared preferences in Activity B.In activity A oncreate() i am fetching the values of the shared preferences to compare with some conditions however it gives me null pointer exception as expected (As i do not go to Activity B).However i want to write a condition to fetch the data from shared preferences if the value is not null.Can some one please say how can i achieve this? Following is my code:
In Activity B:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MerchantLogin.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("showdialog_login", "dontshow");
editor.commit();
In Activity A:
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences prefs =null;
prefs = PreferenceManager.getDefaultSharedPreferences(LoginScreen.this);
SharedPreferences.Editor editor = prefs.edit();
if ((prefs.getString("showdialog_login", null).equalsIgnoreCase("dontshow")))
{
}
else if((prefs.getString("showdialog_login", null).equalsIgnoreCase("true")))
{
}
else if((prefs.getString("showdialog_login", null).equalsIgnoreCase("dummy")))
{
}
else
{
editor.putString("showdialog_login", "false");
editor.commit();
}
}
However i get error at this line:
if ((prefs.getString("showdialog_login", null).equalsIgnoreCase("dontshow"))).How can i execute this block of code.
Instead of :
prefs.getString("showdialog_login", null)
Use:
prefs.getString("showdialog_login", "")
Because, if value for "showdialog_login" preference is not set, it will return null value and you might get NPE (Null pointer exception).
You should always use the constant as the first argument when comparing using equals, i.e.
"dontshow".equalsIgnoreCase(prefs.getString("showdialog_login", null))
You are getting the NullPointerException because the showdialog_login property is not yet set, i.e.
prefs.getString("showdialog_login", null)
returns null, because that's what you set the default value to.
Effectively, your condition is thus
null.equalsIgnoreCase("dontshow")
-which naturally ends up in a NullPointerException.
In Activity A:
static SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState)
{
prefs = getSharedPreferences("showdialog_login",0);
String ss= prefs.getString("showdialog_login", "default");
if ((ss.equalsIgnoreCase("dontshow")))
{
}
else if((ss.equalsIgnoreCase("true")))
{
}
else if((ss.equalsIgnoreCase("dummy")))
{
}
else
{
editor.putString("showdialog_login", "false");
editor.commit();
}
}