How do I save user session using SharedPreferences in Cloud Firestore when I'm not using Firebase authentication?How to attach pdf file from assets in email?Getting an exception when app startsCan someone show me a simple working implementation of PagerSlidingTabStrip?setText on button from another activity androidjava.lang.NullPointerException when invoking onLoadFinished()display data of specific/current/ logged in user in firebase cloudSearch Firestore query don't show data in RecycleViewCloud Firestore Authentication iOSHow to add child(Product) under a child(Store) in Firebase Database using RecyclerView
Why is dry soil hydrophobic? Bad gardener paradox
A DVR algebra with weird automorphisms
Bob's unnecessary trip to the shops
Is a public company able to check out who owns its shares in very detailed format?
What would be the ideal melee weapon made of "Phase Metal"?
Metric version of "footage"?
Can a continent naturally split into two distant parts within a week?
School House Points (Python + SQLite)
Is killing off one of my queer characters homophobic?
How do Windows version numbers work?
Why is the total number of hard disk sectors shown in fdisk not the same as theoretical calculation?
In which ways do anagamis still experience ignorance?
When is pointing out a person's hypocrisy not considered to be a logical fallacy?
Why the term 'unified' in "unified mass unit"?
What are some symbols representing peasants/oppressed persons fighting back?
Pre-1968 YA science fiction novel: robot with black-and-white vision, later the robot could see in color
Back to the nineties!
Cubic programming and beyond?
Find values of x so that the matrix is invertible
What does `[$'rn']` mean?
Is this floating-point optimization allowed?
Does Google Maps take into account hills/inclines for route times?
Why did the Japanese attack the Aleutians at the same time as Midway?
how can draw a kiviat diagram?
How do I save user session using SharedPreferences in Cloud Firestore when I'm not using Firebase authentication?
How to attach pdf file from assets in email?Getting an exception when app startsCan someone show me a simple working implementation of PagerSlidingTabStrip?setText on button from another activity androidjava.lang.NullPointerException when invoking onLoadFinished()display data of specific/current/ logged in user in firebase cloudSearch Firestore query don't show data in RecycleViewCloud Firestore Authentication iOSHow to add child(Product) under a child(Store) in Firebase Database using RecyclerView
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
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 inside the document as well.
So when a user logins, their entered email is checked against a document ID matching that email, if it exists it will log in and display user control panel.
Now after the login, I need to somehow create a user session, so that the user can never go back to the login screen until he logouts. In case the app crashes or lost network connection, a saved user session would be very useful.
Here's my code for the login activity:
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import static com.basgeekball.awesomevalidation.ValidationStyle.BASIC;
public class SLogin extends AppCompatActivity
public static final String STUDENT_EMAIL = "student_email";
private EditText tEmail;
private EditText tPassword;
private String email = "";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference dbUsers;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slogin);
tEmail= findViewById(R.id.Email);
tEmail.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
email = s.toString();
@Override
public void afterTextChanged(Editable s)
);
tPassword=findViewById(R.id.Password);
// Here you simply set saveEmail to empty string because at this moment when activity is
// created (onCreate) tEmail field is empty. To update this field dynamically you need set
// addTextChangedListener on tEmail.
// saveEmail=tEmail.getText().toString();
dbUsers = db.collection("Students");
//Validation Method
private boolean validate()
AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
mAwesomeValidation.addValidation(tEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[~`!@#\$%\^&\*\(\)\-_\+=\\\[\]\
//Method to check password matching or not
private void passCheck(@NonNull DocumentSnapshot snapshot)
final String uPass = tPassword.getText().toString();
final String storedPass = snapshot.getString("password");
if (storedPass != null && storedPass.equals(uPass))
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();
public void sLogin(View v)
if (validate())
DocumentReference dbDocs = dbUsers.document(email);
dbDocs.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task)
if (task.isSuccessful())
DocumentSnapshot document = task.getResult();
if (document != null && document.exists())
//Toast.makeText(SLogin.this, "You are registered", Toast.LENGTH_LONG).show();
// Improved password checking because at first glance I
// don't see why you call db fetch again to get document
// because if we are here that means we got matching data
// and now we only need to check if password match. No need
// to call get on db again.
//
// It's possible to even more optimize calls to DB in case
// of wrongly typed password. We can cache input email and
// returned password for that email so in case if user
// doesn't change email, but types only password again we
// can compare newly typed password with cached password
// from previous request so we don't make again new DB
// request to simply get again same saved password.
//
// Currently I haven't implemented caching. It's only idea
// to think about in future.
passCheck(document);
else
Toast.makeText(SLogin.this, "You are not registered", Toast.LENGTH_LONG).show();
else
Toast.makeText(SLogin.this, "Unable to connect to database", Toast.LENGTH_LONG).show();
);
public void nUser(View v)
Intent intent = new Intent(SLogin.this, RegisterActivity.class);
startActivity(intent);
java android google-cloud-firestore sharedpreferences usersession
add a comment |
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 inside the document as well.
So when a user logins, their entered email is checked against a document ID matching that email, if it exists it will log in and display user control panel.
Now after the login, I need to somehow create a user session, so that the user can never go back to the login screen until he logouts. In case the app crashes or lost network connection, a saved user session would be very useful.
Here's my code for the login activity:
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import static com.basgeekball.awesomevalidation.ValidationStyle.BASIC;
public class SLogin extends AppCompatActivity
public static final String STUDENT_EMAIL = "student_email";
private EditText tEmail;
private EditText tPassword;
private String email = "";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference dbUsers;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slogin);
tEmail= findViewById(R.id.Email);
tEmail.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
email = s.toString();
@Override
public void afterTextChanged(Editable s)
);
tPassword=findViewById(R.id.Password);
// Here you simply set saveEmail to empty string because at this moment when activity is
// created (onCreate) tEmail field is empty. To update this field dynamically you need set
// addTextChangedListener on tEmail.
// saveEmail=tEmail.getText().toString();
dbUsers = db.collection("Students");
//Validation Method
private boolean validate()
AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
mAwesomeValidation.addValidation(tEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[~`!@#\$%\^&\*\(\)\-_\+=\\\[\]\
//Method to check password matching or not
private void passCheck(@NonNull DocumentSnapshot snapshot)
final String uPass = tPassword.getText().toString();
final String storedPass = snapshot.getString("password");
if (storedPass != null && storedPass.equals(uPass))
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();
public void sLogin(View v)
if (validate())
DocumentReference dbDocs = dbUsers.document(email);
dbDocs.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task)
if (task.isSuccessful())
DocumentSnapshot document = task.getResult();
if (document != null && document.exists())
//Toast.makeText(SLogin.this, "You are registered", Toast.LENGTH_LONG).show();
// Improved password checking because at first glance I
// don't see why you call db fetch again to get document
// because if we are here that means we got matching data
// and now we only need to check if password match. No need
// to call get on db again.
//
// It's possible to even more optimize calls to DB in case
// of wrongly typed password. We can cache input email and
// returned password for that email so in case if user
// doesn't change email, but types only password again we
// can compare newly typed password with cached password
// from previous request so we don't make again new DB
// request to simply get again same saved password.
//
// Currently I haven't implemented caching. It's only idea
// to think about in future.
passCheck(document);
else
Toast.makeText(SLogin.this, "You are not registered", Toast.LENGTH_LONG).show();
else
Toast.makeText(SLogin.this, "Unable to connect to database", Toast.LENGTH_LONG).show();
);
public void nUser(View v)
Intent intent = new Intent(SLogin.this, RegisterActivity.class);
startActivity(intent);
java android google-cloud-firestore sharedpreferences usersession
add a comment |
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 inside the document as well.
So when a user logins, their entered email is checked against a document ID matching that email, if it exists it will log in and display user control panel.
Now after the login, I need to somehow create a user session, so that the user can never go back to the login screen until he logouts. In case the app crashes or lost network connection, a saved user session would be very useful.
Here's my code for the login activity:
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import static com.basgeekball.awesomevalidation.ValidationStyle.BASIC;
public class SLogin extends AppCompatActivity
public static final String STUDENT_EMAIL = "student_email";
private EditText tEmail;
private EditText tPassword;
private String email = "";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference dbUsers;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slogin);
tEmail= findViewById(R.id.Email);
tEmail.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
email = s.toString();
@Override
public void afterTextChanged(Editable s)
);
tPassword=findViewById(R.id.Password);
// Here you simply set saveEmail to empty string because at this moment when activity is
// created (onCreate) tEmail field is empty. To update this field dynamically you need set
// addTextChangedListener on tEmail.
// saveEmail=tEmail.getText().toString();
dbUsers = db.collection("Students");
//Validation Method
private boolean validate()
AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
mAwesomeValidation.addValidation(tEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[~`!@#\$%\^&\*\(\)\-_\+=\\\[\]\
//Method to check password matching or not
private void passCheck(@NonNull DocumentSnapshot snapshot)
final String uPass = tPassword.getText().toString();
final String storedPass = snapshot.getString("password");
if (storedPass != null && storedPass.equals(uPass))
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();
public void sLogin(View v)
if (validate())
DocumentReference dbDocs = dbUsers.document(email);
dbDocs.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task)
if (task.isSuccessful())
DocumentSnapshot document = task.getResult();
if (document != null && document.exists())
//Toast.makeText(SLogin.this, "You are registered", Toast.LENGTH_LONG).show();
// Improved password checking because at first glance I
// don't see why you call db fetch again to get document
// because if we are here that means we got matching data
// and now we only need to check if password match. No need
// to call get on db again.
//
// It's possible to even more optimize calls to DB in case
// of wrongly typed password. We can cache input email and
// returned password for that email so in case if user
// doesn't change email, but types only password again we
// can compare newly typed password with cached password
// from previous request so we don't make again new DB
// request to simply get again same saved password.
//
// Currently I haven't implemented caching. It's only idea
// to think about in future.
passCheck(document);
else
Toast.makeText(SLogin.this, "You are not registered", Toast.LENGTH_LONG).show();
else
Toast.makeText(SLogin.this, "Unable to connect to database", Toast.LENGTH_LONG).show();
);
public void nUser(View v)
Intent intent = new Intent(SLogin.this, RegisterActivity.class);
startActivity(intent);
java android google-cloud-firestore sharedpreferences usersession
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 inside the document as well.
So when a user logins, their entered email is checked against a document ID matching that email, if it exists it will log in and display user control panel.
Now after the login, I need to somehow create a user session, so that the user can never go back to the login screen until he logouts. In case the app crashes or lost network connection, a saved user session would be very useful.
Here's my code for the login activity:
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import static com.basgeekball.awesomevalidation.ValidationStyle.BASIC;
public class SLogin extends AppCompatActivity
public static final String STUDENT_EMAIL = "student_email";
private EditText tEmail;
private EditText tPassword;
private String email = "";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference dbUsers;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slogin);
tEmail= findViewById(R.id.Email);
tEmail.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
email = s.toString();
@Override
public void afterTextChanged(Editable s)
);
tPassword=findViewById(R.id.Password);
// Here you simply set saveEmail to empty string because at this moment when activity is
// created (onCreate) tEmail field is empty. To update this field dynamically you need set
// addTextChangedListener on tEmail.
// saveEmail=tEmail.getText().toString();
dbUsers = db.collection("Students");
//Validation Method
private boolean validate()
AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
mAwesomeValidation.addValidation(tEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[~`!@#\$%\^&\*\(\)\-_\+=\\\[\]\
//Method to check password matching or not
private void passCheck(@NonNull DocumentSnapshot snapshot)
final String uPass = tPassword.getText().toString();
final String storedPass = snapshot.getString("password");
if (storedPass != null && storedPass.equals(uPass))
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();
public void sLogin(View v)
if (validate())
DocumentReference dbDocs = dbUsers.document(email);
dbDocs.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task)
if (task.isSuccessful())
DocumentSnapshot document = task.getResult();
if (document != null && document.exists())
//Toast.makeText(SLogin.this, "You are registered", Toast.LENGTH_LONG).show();
// Improved password checking because at first glance I
// don't see why you call db fetch again to get document
// because if we are here that means we got matching data
// and now we only need to check if password match. No need
// to call get on db again.
//
// It's possible to even more optimize calls to DB in case
// of wrongly typed password. We can cache input email and
// returned password for that email so in case if user
// doesn't change email, but types only password again we
// can compare newly typed password with cached password
// from previous request so we don't make again new DB
// request to simply get again same saved password.
//
// Currently I haven't implemented caching. It's only idea
// to think about in future.
passCheck(document);
else
Toast.makeText(SLogin.this, "You are not registered", Toast.LENGTH_LONG).show();
else
Toast.makeText(SLogin.this, "Unable to connect to database", Toast.LENGTH_LONG).show();
);
public void nUser(View v)
Intent intent = new Intent(SLogin.this, RegisterActivity.class);
startActivity(intent);
java android google-cloud-firestore sharedpreferences usersession
java android google-cloud-firestore sharedpreferences usersession
asked Mar 26 at 5:57
DarkNateDarkNate
266 bronze badges
266 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
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
Hi, I get an error message inside PrefUtilities class, Cannot resolve symbol "pref_key_user_status"
– DarkNate
Mar 26 at 7:37
@DarkNate declare pref_key_user_status inside strings.xml file or replace context.getString(R.string.pref_key_user_status) with "pref_key_user_status"
– Vamsi Smart
Mar 26 at 7:47
Hey how do I store that "email" variable on local storage? Because it gets cleared after the app is closed and restarted, any ideas? It's bascially an ID for identifying users in the app and to read data back from the database.
– DarkNate
Mar 26 at 9:57
1
@DarkNate add those two methods in PrefUtilities public void saveUserEmail(String userEmai) preferences.edit().putString(context.getString(R.string.pref_key_user_email),userEmail).apply(); public String getUserEmail() return preferences.getString(context.getString(R.string.pref_key_user_email),""); And use same way as saving login status. If answer is useful consider accepting answer
– Vamsi Smart
Mar 26 at 11:01
It's working and your answer is accepted. Thanks for the help.
– DarkNate
Mar 26 at 11:18
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55350678%2fhow-do-i-save-user-session-using-sharedpreferences-in-cloud-firestore-when-im-n%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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
Hi, I get an error message inside PrefUtilities class, Cannot resolve symbol "pref_key_user_status"
– DarkNate
Mar 26 at 7:37
@DarkNate declare pref_key_user_status inside strings.xml file or replace context.getString(R.string.pref_key_user_status) with "pref_key_user_status"
– Vamsi Smart
Mar 26 at 7:47
Hey how do I store that "email" variable on local storage? Because it gets cleared after the app is closed and restarted, any ideas? It's bascially an ID for identifying users in the app and to read data back from the database.
– DarkNate
Mar 26 at 9:57
1
@DarkNate add those two methods in PrefUtilities public void saveUserEmail(String userEmai) preferences.edit().putString(context.getString(R.string.pref_key_user_email),userEmail).apply(); public String getUserEmail() return preferences.getString(context.getString(R.string.pref_key_user_email),""); And use same way as saving login status. If answer is useful consider accepting answer
– Vamsi Smart
Mar 26 at 11:01
It's working and your answer is accepted. Thanks for the help.
– DarkNate
Mar 26 at 11:18
add a comment |
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
Hi, I get an error message inside PrefUtilities class, Cannot resolve symbol "pref_key_user_status"
– DarkNate
Mar 26 at 7:37
@DarkNate declare pref_key_user_status inside strings.xml file or replace context.getString(R.string.pref_key_user_status) with "pref_key_user_status"
– Vamsi Smart
Mar 26 at 7:47
Hey how do I store that "email" variable on local storage? Because it gets cleared after the app is closed and restarted, any ideas? It's bascially an ID for identifying users in the app and to read data back from the database.
– DarkNate
Mar 26 at 9:57
1
@DarkNate add those two methods in PrefUtilities public void saveUserEmail(String userEmai) preferences.edit().putString(context.getString(R.string.pref_key_user_email),userEmail).apply(); public String getUserEmail() return preferences.getString(context.getString(R.string.pref_key_user_email),""); And use same way as saving login status. If answer is useful consider accepting answer
– Vamsi Smart
Mar 26 at 11:01
It's working and your answer is accepted. Thanks for the help.
– DarkNate
Mar 26 at 11:18
add a comment |
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
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
edited Mar 26 at 6:33
answered Mar 26 at 6:24
Vamsi SmartVamsi Smart
7638 silver badges15 bronze badges
7638 silver badges15 bronze badges
Hi, I get an error message inside PrefUtilities class, Cannot resolve symbol "pref_key_user_status"
– DarkNate
Mar 26 at 7:37
@DarkNate declare pref_key_user_status inside strings.xml file or replace context.getString(R.string.pref_key_user_status) with "pref_key_user_status"
– Vamsi Smart
Mar 26 at 7:47
Hey how do I store that "email" variable on local storage? Because it gets cleared after the app is closed and restarted, any ideas? It's bascially an ID for identifying users in the app and to read data back from the database.
– DarkNate
Mar 26 at 9:57
1
@DarkNate add those two methods in PrefUtilities public void saveUserEmail(String userEmai) preferences.edit().putString(context.getString(R.string.pref_key_user_email),userEmail).apply(); public String getUserEmail() return preferences.getString(context.getString(R.string.pref_key_user_email),""); And use same way as saving login status. If answer is useful consider accepting answer
– Vamsi Smart
Mar 26 at 11:01
It's working and your answer is accepted. Thanks for the help.
– DarkNate
Mar 26 at 11:18
add a comment |
Hi, I get an error message inside PrefUtilities class, Cannot resolve symbol "pref_key_user_status"
– DarkNate
Mar 26 at 7:37
@DarkNate declare pref_key_user_status inside strings.xml file or replace context.getString(R.string.pref_key_user_status) with "pref_key_user_status"
– Vamsi Smart
Mar 26 at 7:47
Hey how do I store that "email" variable on local storage? Because it gets cleared after the app is closed and restarted, any ideas? It's bascially an ID for identifying users in the app and to read data back from the database.
– DarkNate
Mar 26 at 9:57
1
@DarkNate add those two methods in PrefUtilities public void saveUserEmail(String userEmai) preferences.edit().putString(context.getString(R.string.pref_key_user_email),userEmail).apply(); public String getUserEmail() return preferences.getString(context.getString(R.string.pref_key_user_email),""); And use same way as saving login status. If answer is useful consider accepting answer
– Vamsi Smart
Mar 26 at 11:01
It's working and your answer is accepted. Thanks for the help.
– DarkNate
Mar 26 at 11:18
Hi, I get an error message inside PrefUtilities class, Cannot resolve symbol "pref_key_user_status"
– DarkNate
Mar 26 at 7:37
Hi, I get an error message inside PrefUtilities class, Cannot resolve symbol "pref_key_user_status"
– DarkNate
Mar 26 at 7:37
@DarkNate declare pref_key_user_status inside strings.xml file or replace context.getString(R.string.pref_key_user_status) with "pref_key_user_status"
– Vamsi Smart
Mar 26 at 7:47
@DarkNate declare pref_key_user_status inside strings.xml file or replace context.getString(R.string.pref_key_user_status) with "pref_key_user_status"
– Vamsi Smart
Mar 26 at 7:47
Hey how do I store that "email" variable on local storage? Because it gets cleared after the app is closed and restarted, any ideas? It's bascially an ID for identifying users in the app and to read data back from the database.
– DarkNate
Mar 26 at 9:57
Hey how do I store that "email" variable on local storage? Because it gets cleared after the app is closed and restarted, any ideas? It's bascially an ID for identifying users in the app and to read data back from the database.
– DarkNate
Mar 26 at 9:57
1
1
@DarkNate add those two methods in PrefUtilities public void saveUserEmail(String userEmai) preferences.edit().putString(context.getString(R.string.pref_key_user_email),userEmail).apply(); public String getUserEmail() return preferences.getString(context.getString(R.string.pref_key_user_email),""); And use same way as saving login status. If answer is useful consider accepting answer
– Vamsi Smart
Mar 26 at 11:01
@DarkNate add those two methods in PrefUtilities public void saveUserEmail(String userEmai) preferences.edit().putString(context.getString(R.string.pref_key_user_email),userEmail).apply(); public String getUserEmail() return preferences.getString(context.getString(R.string.pref_key_user_email),""); And use same way as saving login status. If answer is useful consider accepting answer
– Vamsi Smart
Mar 26 at 11:01
It's working and your answer is accepted. Thanks for the help.
– DarkNate
Mar 26 at 11:18
It's working and your answer is accepted. Thanks for the help.
– DarkNate
Mar 26 at 11:18
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55350678%2fhow-do-i-save-user-session-using-sharedpreferences-in-cloud-firestore-when-im-n%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown