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

public class PrefUtilities {

private SharedPreferences preferences;
Context context;


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


public static PrefUtilities with(Context context){
    return new PrefUtilities(context);
}


public void setUserLogin(boolean isUserLogedin){

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

}

public boolean isUserLogedin(){
    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

private void passCheck(@NonNull DocumentSnapshot snapshot)
{
    final String uPass = tPassword.getText().toString();
    final String storedPass = snapshot.getString("password");
    if (storedPass != null && storedPass.equals(uPass))
    {

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

        Intent intent = new Intent(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?"