-3

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?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Gabriel
  • 464
  • 4
  • 17

2 Answers2

1

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) {

    }
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
0

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

Ali Kaissi
  • 44
  • 8