I am trying to remember a user's login credentials so that after he/she logs into the application the first time, each subsequent time, it automatically logs him/her in and starts the main activity.
Right now I have two activities the Login activity and the Main app activity. When a user types in his/hers credentials, it verifies them against the DB on my server in an AsyncTask. Now I am using Shared Prefs to store the username and password and each time the app is started I want to read those prefs. If they are empty, then open the Login activity/screen, otherwise open the Main activity/screen.
This works....but it takes about 3-5 seconds before it opens the Main activity. So it starts out on the Login activity and then after 3-5 seconds it goes to the Main activity. The following code is in the Login activity....where should I put it so that it does not open the Login activity unless the prefs are blank?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_login);
//keep screen on while activity is running
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
//get username and password from preferences if they exist
sharedPrefs = getSharedPreferences(PREFERENCES, getApplicationContext().MODE_PRIVATE);
if (sharedPrefs.contains(UserId) && sharedPrefs.contains(Password))
{
inputEmail.setText(sharedPrefs.getString(UserId, ""));
inputPassword.setText(sharedPrefs.getString(Password, ""));
new MyAsyncTask().execute(sharedPrefs.getString(UserId, ""),
sharedPrefs.getString(Password, ""));
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
Editor editor = sharedPrefs.edit();
editor.putString(UserId, email);
editor.putString(Password, password);
editor.commit();
new MyAsyncTask().execute(email, password);
}
});
}
Thanks for the help!
Related
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.
My first application in android studio and i want to do this:
Description:
username:username (TextBox)
password:password (TextBox)
Keep me logged in -->CheckBox
LOGIN -->BUTTON
The first time where the user enters your username and password and click to Keep me logged in the application must be remember the username and password without the user writes again in the second time.
Could anyone give me some idea how this implement in android, I found many examples but nothing work.
You could use SharedPreferences to remember the user preference. Here it is a boolean.
SharedPreferences prefs = getDefaultSharedPreferences(this);
boolean keepLoggedIn = prefs.getBoolean(KEY_KEEP_LOGGED_IN, false);
//After user makes the selection on the checkbox,
SharedPreferences.Editor editor = getDefaultSharedPreferences(this).edit();
editor.putBoolean(KEY_KEEP_LOGGED_IN, true);
editor.commit();
I did something very similar to this recently
First, make sure to initialize your fields in question
AutoCompleteTextView mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
EditText mPasswordView = (EditText) findViewById(R.id.password);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
Set your onClick event:
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
In order for the user password to be remembered, you have to save them somewhere. I stored them in shared preferences, but you can use a more secure method depending on your application or even encrypt before storing them http://developer.android.com/guide/topics/data/data-storage.html#pref
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Put the strings in the editor
editor.putString(getString(R.string.userAccount), email);
editor.putString(getString(R.string.password), password);
Now in onCreate or your other favorite android start method (depending on if you're using a fragment or activity), retrieve them
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
//Retrive the values
sharedPref.getString(getString(R.string.userAccount), "")
sharedPref.getString(getString(R.string.password), "")
I am Creating an app where i login into app,it matches the data with database and then permits the user to login. But every time i press on login and go to another activity , the application terminates
public void userlogin(View view){
logname = et1.getText().toString();//retrieving details from Username field
logpass = et2.getText().toString();//retrieving details from Password field
String method = "Login";
BackTask bt = new BackTask(this);
bt.execute(method,logname,logpass);//checking from database
SharedPreferences.Editor editor = sharedpreferences.edit();//session management
editor.putString(Name, logname);
editor.putString(Pass, logpass);
if(editor.commit())
{
Intent in = new Intent(MainActivity.this,Create.class);
startActivity(in);
}
//starting another activty
}
I am developing android application with login. When the user logged in i want to pass both username and password to another activity in another edittext. The passed username and password should be displayed in the another edittext of another activity. the password should look as it is (not revealing characters). I know that it may sound like weird but is that possible? Just give me an answer i know you might ask why should i display this thing to another edittext but i have my own purpose.
This is what i need to pass to another edittext
inputusername = (EditText) findViewById(R.id.loginUsername);
inputPassword = (EditText) findViewById(R.id.loginPasswod);
imgLogin1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = inputusername.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(username, password);
// check for login response
try {
if (json.getString(KEY_PSUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_PSUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_PUSERNAME), json.getString(KEY_PUID), json_user.getString(KEY_PCREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), PatientHomeActivity.class);
dashboard.putExtra(KEY_PUSERNAME,username);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
EDIT
Here's where i have passed the data
private static final String TAG_PUSERNAME = "username";
private static final String TAG_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* Start and bind the imService
**/
startService(new Intent(Login.this, IMService.class));
setContentView(R.layout.login_screen);
setTitle("Login");
Bundle i = getIntent().getExtras();
Button loginButton = (Button) findViewById(R.id.login);
cancelButton = (Button) findViewById(R.id.cancel_login);
usernameText = (EditText) findViewById(R.id.userName);
usernameText.setText(i.getString(TAG_PUSERNAME));
passwordText = (EditText) findViewById(R.id.password);
passwordText.setText(i.getString(TAG_PASSWORD));
That's the next activity where the data should be passed.
Use Bundle to pass the value from current activity to next acivity
Current Activtiy to pass data
Intent i = new Intent (BundleActivity.this,datapass.class);
Bundle b =new Bundle();
b.putString("Username","your Username editext value");
b.putString("Password","your Password editext value");
i.putExtras(b);
startActivity(i);
In Next activity to receive data
Bundle b = getIntent().getExtras();
String Username= b.getString("Username");
String Password= b.getString("Password");
For passing data from onr activity to other you can use intents or shared preference.
For setting password as non revealing character in edit textbox :Set this android:inputType="phone" to editbox of your second activity in which you are showing password in Xml Layout OR from your activity you can also dynamically set this as userPassword.setInputType(129)(it will make text into password ).Hope it will help.
I have created a login for an application. I got it that if you type in the username and password then click on the checkbox it remembers the username and password. However, if you make any changes after you click the checkbox the they are not saved. I am wondering if there is a way to fix this and how would I got about doing this. What I am thinking is when click on the edittext it continually saves what is in the editext. Basically, something that would dynamically saves while the user changes the password or username while the checkbox is clicked.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_log_in);
SharedPreferences.Editor editor;
name = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
button = (Button) findViewById(R.id.Button01);
error = (TextView) findViewById(R.id.invalid);
error.setVisibility(View.INVISIBLE);
checkbox = (CheckBox) findViewById(R.id.remember);
LoadPreferences();
LoadPreferences1();
}
public void rememberInfo(View view) {
SavePrefernces("MEM1", name.getText().toString());
SavePrefernces("MEM2", password.getText().toString());
}
private void LoadPreferences1() {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem2 = shardPreferences.getString("MEM2", "");
password.setText(strSavedMem2);
}
private void LoadPreferences() {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = shardPreferences.getString("MEM1", "");
name.setText(strSavedMem1);
}
private void SavePrefernces(String key, String value) {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = shardPreferences.edit();
editor.putString(key, value);
editor.commit();
}
The simplest solution I think would be to do the saving of the login details at the time of pressing the login (or whatever) button. So when the button is pressed, get the values from both the EditTexts and store them in the SharedPreferences.
I believe you are calling Saveprefernces when the checkBox is checked. Instead you should do it once you know that your sign In is success, so that only a valid pair of username:password is saved