Skip to content Skip to sidebar Skip to footer

How Do I Save User Session Using Sharedpreferences In Cloud Firestore When I'm Not Using Firebase Authentication?

When a user registers in my Android app, their data is stored inside a collection, where the document ID is their email address which helps find a user. The password is stored insi

Solution 1:

For best practice add the following class

publicclassPrefUtilities {

privateSharedPreferences preferences;
Context context;


privatePrefUtilities(Context context) {
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    this.context = context;
}


publicstaticPrefUtilitieswith(Context context){
    returnnewPrefUtilities(context);
}


publicvoidsetUserLogin(boolean isUserLogedin){

    preferences.edit().putBoolean(context.getString(R.string.pref_key_user_status),isUserLogedin).apply();

}

publicbooleanisUserLogedin(){
    return preferences.getBoolean(context.getString(R.string.pref_key_user_status),false);
}


}

check for login status inside onCreate method

if(PrefUtilities.with(this).isUserLogedin()){

   Intent intent = new Intent(SLogin.this, StudentCP.class);
        intent.putExtra(STUDENT_EMAIL, email);
        startActivity(intent);
}

Save login status inside passCheck method

privatevoidpassCheck(@NonNull DocumentSnapshot snapshot)
{
    finalStringuPass= tPassword.getText().toString();
    finalStringstoredPass= snapshot.getString("password");
    if (storedPass != null && storedPass.equals(uPass))
    {

         PrefUtilities.with(this).setUserLogin(true);       

        Intentintent=newIntent(SLogin.this, StudentCP.class);
        intent.putExtra(STUDENT_EMAIL, email);
        startActivity(intent);
    }
    else
    {
        Toast.makeText(SLogin.this, "Invalid Password!", Toast.LENGTH_LONG).show();
    }
}

When user logout use bellow method to change SharedPreferences

PrefUtilities.with(this).setUserLogin(false);

You can also add other methods in PrefUtilities class saving user Email

Post a Comment for "How Do I Save User Session Using Sharedpreferences In Cloud Firestore When I'm Not Using Firebase Authentication?"