0

does someone know where the mistake is? There is an error in Android Studio.

The following is the code for now.

final String keyFirstTime = "keyFirstTime";

prefsEditor.putBoolean(keyFirstTime, false);

if (keyFirstTime = false) {

Thanks in advance.

quidproquo
  • 27
  • 9
  • 2
    Well, `keyFirstTime` is a `String`, so you can't assign a boolean value to it. And the expression in an `if` statement needs to be of `boolean` (or `Boolean`) type too. – Andy Turner Jan 18 '17 at 16:36
  • Show full code please. – Yoleth Jan 18 '17 at 16:37
  • @BalkrishnaRawool nope, that's still a compiler error, because strings are never identical to booleans. – Andy Turner Jan 18 '17 at 16:39
  • @BalkrishnaRawool and I'm saying that your suggestion is incorrect: it's just replacing one compiler error with another. – Andy Turner Jan 18 '17 at 16:41
  • there is an error for **prefs.getBoolean(keyFirstTime) = false** too – quidproquo Jan 18 '17 at 16:42
  • Your code doesn't contain `prefs.getBoolean(keyFirstTime) = false`. But that would be an error because you can only assign to a variable; method results aren't variables. – Andy Turner Jan 18 '17 at 16:46

2 Answers2

2
  1. keyFirstTime is a string (see comment)
  2. you are PUTTING a value not getting a value
  3. You are using an assignment in an if statement
  4. You are comparing a STRING to a BOOLEAN

In Activity 1 you should have:

final String keyFirstTime = "keyFirstTime";
prefsEditor.putBoolean(keyFirstTime, false);

In Activity 2 you should have:

boolean firstTime = prefs.getBoolean(keyFirstTime, false); //you don't need the editor
if (firstTime) {
    ...
}

Please go here for a tutorial: https://developer.android.com/training/basics/data-storage/shared-preferences.html

EDIT Try doing this (stolen from here)

private static final String FIRST_RUN = "FIRST_RUN";
SharedPreferences prefs = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    prefs = getSharedPreferences(getApplicationContext().getPackageName(), MODE_PRIVATE);
}

@Override
protected void onResume() {
    super.onResume();

    if (prefs.getBoolean(FIRST_RUN, true)) {           
        prefs.edit().putBoolean(FIRST_RUN, false).commit();
        //call relevant function for first run
    } else {
        //call relevant function for every other run
    }
}
Community
  • 1
  • 1
Quintin Balsdon
  • 5,484
  • 10
  • 54
  • 95
-1
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();  prefs.edit().putBoolean("keyFirstTime", true).commit();

Now to get Boolean value you have to use

Boolean check = prefs.getBoolean("keyFirstTime", false);

Now you can check this way

if(check){ your code here }

TysonSubba
  • 1,362
  • 2
  • 12
  • 16