Home > Mobile >  SharedPreferences is never null even when empty
SharedPreferences is never null even when empty

Time:10-10

I'm trying to toast "No user saved" when the login button is clicked and the SharedPreferences has nothing saved in it. But when I use this code, it always proceeds to the else statement even if SharedPreferences is empty:

btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick (View v) {

        SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);

        if (preferences == null){
            Toast.makeText(MainActivity.this, "No user saved", Toast.LENGTH_SHORT).show();}

MY_PREFS.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map />

Is there a better way to write the if-statement?

CodePudding user response:

when you obtain SharedPreferences instance app will create empty file, so it will always exists and won't be null, as you may call then edit() and put some initial data in it. But before modifying this file you can check which keys are already inside

Map<String, ?> storedValues = preferences.getAll();
int numberOfStoredValues = storedValues.size();

numberOfStoredValues will be obviusly 0 when there is nothing stored in it (yet). so your if should look like below

if (preferences.getAll().size() == 0)
        Toast.makeText(MainActivity.this, "No user saved", Toast.LENGTH_SHORT).show();

note that you can also check that some particular key already exists in these preferences, e.g. login is stored

if (preferences.contains(KEY_LOGIN))

CodePudding user response:

Sir Once you clear the SharedPreference and than try

SharedPreferences sp = getSharedPreferences("MYKEY",0);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.commit();
  • Related