Remember Users in android - android

I am developing an Android App. It has a login page.. what is the best way to save users' details so they do not have to fill in their credentials every time they use the app..
according to Link ? we can use account manager or oath2. I am still not sure of which methods i can use.. I simply want the user to enter a username and a password once.. I came across other methods but I am looking for the best method to be used.

You can use this function to save username and password
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences shared = getSharedPreferences("shared", MODE_PRIVATE);
if(shared.contains("username") && shared.contains("password")){
startingActivity();
} else {
saveInformation(userId,pass);
}
}
public void saveInformation(String username,String password) {
SharedPreferences shared = getSharedPreferences("shared", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
}

Related

My app stayed logged in even after restart

I am making simple login app for my homework project.I wanted to user stay loged in
after my app is destroyed.I managed that but now he is always loged in even without entering email and password.I wanted to be able to stay loged in until he press log out button,but even he press it he will go back to log in page but when app is restarted it is again loged in
i tried this: How to keep android applications always be logged in state?
log in page:
public class MainActivity extends AppCompatActivity {
private EditText email, password;
private SharedPreferences sharedPreferences;
public static final String PREF_NAME = "sp_name";
ConstraintLayout constraintLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = findViewById(R.id.email_view);
password = findViewById(R.id.pass_view);
constraintLayout = findViewById(R.id.activity_main);
sharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
// //uzimam email vrednost iz sharedprefernce
String storedEmail = sharedPreferences.getString("EMAIL", null);
//uzimam password vrednosti
String storedPass = sharedPreferences.getString("PASSWORD", null);
if(storedEmail != null && storedPass != null){
// login automatically with username and password
goToPocetnaStranica();
}
Button loginButton = findViewById(R.id.login_button);
//kada je dugme za login stisnuto loguje se na pocetnu stanu i skladisti login informacije
//u sharedpreference tak da sledeci put moze da se autologuje bez ponovnog unosa login informacija
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//uzimam email i password
String getEmail = email.getText().toString();
String getPass = password.getText().toString();
//proveravam da li je neko polje prazno
if (TextUtils.isEmpty(getEmail) || TextUtils.isEmpty(getPass)) {
Toast.makeText(MainActivity.this, R.string.obavestenje_za_unos, Toast.LENGTH_SHORT).show();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("EMAIL", getEmail);
editor.putString("PASSWORD", getPass);
editor.apply();
email.setText("");
password.setText("");
goToPocetnaStranica();
}
}
});
}
private void goToPocetnaStranica(){
Toast.makeText(MainActivity.this, R.string.uspesno_logovanje, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, PocetnaStranica.class);
startActivity(intent);
}
}
and my page afer log in:
public class PocetnaStranica extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pocetna_stranica);
Button logoutButton = findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.remove("PASSWORD");
editor.clear();
editor.apply();
finish();
}
});
}
}
#Sebastian makes a good point saying that you need to use the AND operator in the if statement instead of the OR operator. That's because it checks if the email exists or if the password exists. You as you posted only removed the password, so the email is still there. The program takes it as signed in. Also, instead of independently deleting the password and email, just use:
sharedPreferences.clear() //Clears every single value
That would also help with the removal of cache files and save memory space that is wasted.
Edit:
The error actually is in your second snippet of code. This code to get the shared preferences:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
This does get the default shared preferences, but instead of getting the preferences where you save your email and your password, it returns a whole different set of shared preferences. What you should do instead is this:
SharedPreferences pref = getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It's the same as you do in MainActivity.java and that was the error: it needed to be the same. Here String PREF_NAME = "sp_name";. The preference name/ids, they exist for this exact thing to identify shared preferences.
If you want to learn more about shared preferences and how they work look at the documentation: https://developer.android.com/reference/android/content/SharedPreferences
It seems like in your main activity you are using the OR ( || ) operator when it should be AND ( && ).
Don’t forget to also delete the email from the preferences.

Google signin - Need to permanently save user details on exit

I have integrated Google sign in sample application with my applications Main Activity.
I have a button in my Navigation header to launch login activity.
When I login with my google account, it fetches my name and email Id into Navigation Header.
Now the issue is, if I quit this app, I need to sign in again every time. How can I save the login details.
I have gone through multiple articles which talk about Shared Preference, however shared preference doesn't work for me.
Below is one of the code snippet I have tried. I am calling storeUserDetails() in onBackPressed and getUserDetails() in onCreate().
public void storeUserDetails(String userName, String emailID){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreference.edit();
mEditor.putString("userFullName",userName);
mEditor.putString("userEmailID",emailID);
mEditor.apply();
}
private String getUserDetails(){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
return mSharedPreference.getString("userFullName","#gmail.com");
}
Tried this tutorial as well
https://www.tutorialspoint.com/android/android_shared_preferences.htm
//First instantiate sharedpreferences
SharedPreferences sharedpreferences;
sharedpreferences=getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
private String name,phone,email;
//OnPause method to save shared preferences when activity is destroyed
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, name);
editor.putString(Phone, phone);
editor.putString(Email, email);
editor.commit();
}
//OnResume method used to retrieve sharedpreferences
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
SharedPreferences prefs = this.getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
name = prefs.getString("Name","");
phone = prefs.getString("Phone","");
email = prefs.getString("Email","");
}
Also to handle the login issue, you could use your launcher activity and sharedpreferences to check if Name is null, if it isn't then navigate to your mainactivity, and if it is then navigate to login, then on your logout function just make sure you clear the sharedpreferences.

How to display only one time Login and then after start application directly in android

I am getting trouble in making only one time login... My aim is first user gets login screen.. If he is new user he will register and then login...from then when ever user starts the application he should directly redirect to main activity that is to skip the login page..please friends help me out from this problem..please post me any tutorials or any code...please tell me how to modify in manifest file also...
I am using like this in login activity but i didn't achieve my task.
SharedPreferences pref;
SharedPreferences.Editor editor;
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
editor.putString("register","true");
editor.commit();
String getStatus=pref.getString("register", "nil");
if(getStatus.equals("true"))
// redirect to next activity
else
// show registration page again
Implement your SharedPreferences this way:
Boolean isFirstTime;
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(Splash.this);
SharedPreferences.Editor editor = app_preferences.edit();
isFirstTime = app_preferences.getBoolean("isFirstTime", true);
if (isFirstTime) {
//implement your first time logic
editor.putBoolean("isFirstTime", false);
editor.commit();
}else{
//app open directly
}
check it here
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
A very good example of session management in android app.
Use SharedPreferences. contains which tell an key is present or not in SharedPreferences. Change your code as:
SharedPreferences pref;
SharedPreferences.Editor editor;
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
if(pref.contains("register"))
{
String getStatus=pref.getString("register", "nil");
if(getStatus.equals("true")){
redirect to next activity
}else{
//first time
editor.putString("register","true");
editor.commit();
/// show registration page again
}
}
else{ //first time
editor = pref.edit();
editor.putString("register","true");
editor.commit();
/// show registration page again
}
You can visit my blog
http://upadhyayjiteshandroid.blogspot.in/2013/01/android-working-with-shared-preferences.html
hope you will get the answer and understanding clearly
Boolean flag;
SharedPreferences applicationpreferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = applicationpreferences .edit();
flag = applicationpreferences .getBoolean("flag", false);
if (flag) {
///second time activity
}else{
//first time
editor.putBoolean("flag", true);
editor.commit();
}
Check out the Session Management in Android which shows you the way how you can manage the login if user is already logged into the application or not. And switch the user accordingly.
Hope this will help you.
1.for storing in stored preferences use this
SharedPreferences.Editor editor = getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();
2.for retrieving the same use
SharedPreferences prefs = getSharedPreferences("DeviceToken",
MODE_PRIVATE);
String deviceToken = prefs.getString("DeviceTokenkey", null);

Android login at once

How do I code for login in some app in android that I do not need to login in it again next time I open the application ?
I tried a lot, but no success. If possible please provide me code.
In my app I created a base class for all my activities which checks in oncreate if the user is logged in with shared preferences. If not I show the login screen and continue my app after a successful login.
If this login is local:
First time when you login,
Editor editor= YourSharedPreference.edit();
editor.put(nameOfAccount,name);
editor.put(passwordOfAccount,password);
editor.commit();
Then every time you open the APP,
if(YourSharedPreference.contain(nameOfAccount)&&YourSharedPreference.contain(passwordOfAccount))
{//do not need login}
else
{//do login thing}
An easy way it to store it in the shared preferences.
Basicaly you request a shared preference then you can get string value from it (load).
Using the a SharedPreferences.Editor you can put string value into it (save).
Checking if the value is set (null) will tell you if the user already logged in your app or not.
Here an exemple:
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences("LOGIN_PREF", 0);
String login = settings.getString("login", null);
String password = settings.getString("password", null);
if(login == null || password == null){
// Do stuff for login user
}else{
// Do stuff for not logged user
}
}
public void saveLogin(String password, String login){
SharedPreferences settings = getSharedPreferences("LOGIN_PREF", 0);
SharedPreferences.Editor loginEditor = settings.edit();
loginEditor.putString("login", login);
loginEditor.putString("password", login);
loginEditor.commit();
}

error in saving the username at the launch of application in android

I am developing an android application in which i have to do the following thing
At the start of the app, first thing it should do is ask user to enter name and then through a welcome screen with that name.
Then When the app is used next time it should just give welcome screen (should not ask for name again)
I have created the code for the above.
I have used shared preference saved
My code is
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
But how to check whetehr user is already registered?
Thanks
Tushar
But how to check whetehr user is already registered?
When user starts application first time that time you will check if any preference value exists for name key.
Following snippet will help you
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String namePrefrence = sharedPreferences.getString("uname", "");
if (namePrefrence.length() == 0) {
//User not registered!!
Show dialog where user will enter username
} else {
//User is registered!!
just show welcome screen
}
Well to use SharedPrefernces.. use this::
first declare it...
public static final String PREFS_NAME = "PrefernceNAme";
public static final String PREFS_ITEM = "PrefItemStored";
to get values from it, use:::
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
mode = preferences.getString(PREFS_ITEM, "PrefItemStored");
and to add values in SharedPrefernces, use::
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_ITEM, value)
.commit();

Categories

Resources