Password stored in SharedPreferences not working in android? - android

In this order, this is the procedure I'd like to implement.
1) When imageButton is pressed, it checks the value of "pass" stored in SharedPreferences. If this matches the password, the intent starts the next activity.
2) If it is null, or does not match the password, a dialog box pops up prompting username and password entry.
3) If the entered password is correct, it writes the username and password to SharedPreferences.
4) If the entered password is incorrect, it makes a Toast indicating as such.
Thus far, the login is working perfectly. However, I can't seem to get the SharedPreferences function to work. My code is below:
Button aliaLogin = (Button)findViewById(R.id.imageButton);
aliaLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username","7");
editor.putString("pass","11");
editor.commit();
String username = prefs.getString("username",null);
String pass = prefs.getString("pass",null);
if (pass != null && !pass.isEmpty() && pass.equals(housePass[5])){
Intent intent = new Intent(getApplicationContext(), DisplayHouse.class);
intent.putExtra("Username", username);
startActivity(intent);
}
else {
final Dialog dialog = new Dialog(HouseMain.this);
dialog.setTitle("Login Required!");
dialog.setContentView(R.layout.login_toast);
dialog.show();
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText password = (EditText) dialog.findViewById(R.id.password);
Button submit = (Button) dialog.findViewById(R.id.submitButton);
Button cancel = (Button) dialog.findViewById(R.id.cancelButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = name.getText().toString();
String pass = password.getText().toString();
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (pass.equals(housePass[5])) {
Intent intent = new Intent(getApplicationContext(), DisplayHouse.class);
intent.putExtra("Username", username);
editor.putString("username", username);
editor.putString("pass", pass);
editor.commit();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Incorrect! Impostor alert!", Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
});
cancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
}
});
Could someone tell me what I'm doing wrong?

The problem is each time when you click on the button you are resetting the user name and password to default
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username","7");
editor.putString("pass","11");
editor.commit();
you have to remove it from your code

You have override pass save to Preference file with other pass:
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username","7");
editor.putString("pass","11");
editor.commit();

Related

Android not getting saved sharedPreference value into my edittext

I have two activities one is log in and other is logout when the user logs out I'm sending the email value to the login page and saving that value so the last user should not have to enter it again. The problem is when the user closes the app from the login in activity and reopens it the value of shared Preference is not getting loaded. my code
sign-in activity: I'm getting the value from the log out of the act.
bundle = getIntent().getExtras();
if(bundle != null) {
bundle = getIntent().getExtras();
email = bundle.getString("email");
//Toast.makeText(this, ""+email, Toast.LENGTH_SHORT).show();
}
saving it on onCreate: after getting the value
saveData();
public void saveData() {
Email.setText(email);
SharedPreferences sharedPref = getSharedPreferences("myFile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("email", email);
editor.apply();
//Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show();
}
loading it on onResume:
#Override
public void onResume(){
super.onResume();
SharedPreferences sharedPref = getSharedPreferences("myFile", Context.MODE_PRIVATE);
String text = sharedPref.getString("email", null);
Email.setText(text);
}

How to Retrieve Shared Preferences in Same Activity, It comes Empty?

In my application's login screen, i am fetching a JSON response into the shared preferences in my retrofit2 onResponse method. I get everything as correct from the database and putting as correctly into the shared preferences. I am getting an User_Role from db as string, then based on User_Role, i am directing the user to according activity. I need to reach that User_Role in case R.id.Login: step. In my Logcat i see my response is as i want. I check with Toast after i commit preferences, if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So the only problem i can not retrieve it. Please help.
Because of everything works correctly in my apicall(because i checked every step with Toast.makeText.show(); on screen) i am only putting my LoginActivity.class code below,
LoginActivity.class :
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button bSignUp, bLogin;
EditText etPassword, etEmail;
private ProgressDialog progressDialog;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bSignUp = (Button) findViewById(R.id.bSignUp);
bLogin = (Button) findViewById(R.id.bLogin);
bSignUp.setOnClickListener((View.OnClickListener) this);
bLogin.setOnClickListener((View.OnClickListener) this);
etPassword = (EditText) findViewById(R.id.etPassword);
etEmail = (EditText) findViewById(R.id.etEmail);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Logging in");
progressDialog.setMessage("Please wait ....");
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bSignUp:
Intent SignUpIntent = new Intent(this, SignUpActivity.class);
startActivity(SignUpIntent);
break;
case R.id.bLogin:
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (!email.isEmpty() && !password.isEmpty()) {
progressDialog.show();
loginProcess(email, password);
//Here i need to obtain SharedPreferences that i filled in onResponse Method. It goes directly wrong email or password statement. Because of can't retrieve settings.getString("User_Role","")
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
private void loginProcess(String email, String password) {
LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
call.enqueue(new Callback<UserList>(){
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserList> call, Throwable t) {
Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
Put your SharedPreference logic after onResponse success. it's because it executes before your response get. that's why it empty. so Change code like this
private void checkMethod(){
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
}
And Call this method from onResponse like below
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
checkMethod();
}
Try to start intent condition in the response method. No need to store value in shared preferences.

Android Studio: Shared preference login page still showing and loading on SharedPreference

When I'm logging in on my app my I want my login page will not show anymore if the user is already logged in before. Because everytime a user terminates the app and opens the app again the login page will show with the loading message. I want to implement it because if the user opens the app without data connection the user will still go to his page.
Well here is my code.
pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
boolean hasLoggedIn = pref.getBoolean("hasLoggedIn", false);
if(hasLoggedIn){
String username = pref.getString("username", "");
String password = pref.getString("password", "");
if (!username.equals("") && (!password.equals(""))) {
postData.put("username", username);
postData.put("password", password);
authenticate(postData);
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(etUsername.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPassword.getText().toString())) {
Toast.makeText(LoginActivity.this, "Password is empty", Toast.LENGTH_SHORT).show();
return;
}
editor = pref.edit();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
}
authenticate
private void authenticate(final HashMap<String, String> postData){
PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData,
new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if (s.contains("renter")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, RenterTabs.class);
startActivity(in);
finish();
} else if (s.contains("owner")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, OwnerTabs.class);
startActivity(in);
finish();
} else if (s.contains("driver")) {
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Driver Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, DriverTabs.class);
startActivity(in);
finish();
}else if(s.contains("-1")){
Toast.makeText(LoginActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
}
}
});
task1.execute("http://carkila.esy.es/carkila/authenticate.php");
I don't see why should if(hasLoggedIn) line ever be negative. You always put a true value in hasLoggedIn shared preferences and then you have an if statement on that.
So what I've understood so far is, you want to click the login button automatically when some user is already logged in your application before using the username and the password stored in the SharedPreferences. So if I'm assuming the problem correctly, here's how you can implement this.
I'm just rewriting your code. See the comments for better understanding.
pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
boolean hasLoggedIn = pref.getBoolean("hasLoggedIn", false);
// Move the onClickListener outside the if statement
// Because, if the user is not already logged in
// Then you need to have a click action on this button.
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(etUsername.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPassword.getText().toString())) {
Toast.makeText(LoginActivity.this, "Password is empty", Toast.LENGTH_SHORT).show();
return;
}
editor = pref.edit();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
if(hasLoggedIn) {
String username = pref.getString("username", "");
String password = pref.getString("password", "");
// Remove this
// if (!username.equals("") && (!password.equals(""))) {
// postData.put("username", username);
// postData.put("password", password);
// authenticate(postData);
// }
// Simply put this in here
btnLogin.performClick();
}
And save the preference after a successful login in the authenticate function
private void authenticate(...) {
// On a successful login
editor = pref.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
}

Android Studio SharedPreference Saving Login to Database

I want to save the the user's login details when they first login the mobile application into my Device table and have them bypass the login screen every time the application opens.
I think I've got that part going it's just saving the variables I'm not understanding. My question is how and where should I begin saving the user's detail?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// declaring variebles
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword= (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
etIpAddress = (EditText) findViewById(R.id.etIpAddress);
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
String ipAddress = etIpAddress.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (sharedPreferences.contains("ip")) {
performLogin(username, password, sharedPreferences.getString("ip", ipAddress));
}
// setting up things for login button
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ipAddress = etIpAddress.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("ip", ipAddress);
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
performLogin(username, password, ipAddress);
}
});
}
Here:
performLogin(username, password, sharedPreferences.getString("ip", ipAddress));
user getting login fail because both username and password is passing empty value to performLogin every-time when starting Activity.
In same way as getting ip also get username and password from SharedPreferences like:
if (sharedPreferences.contains("ip")) {
String strUsername=sharedPreferences.getString("username", "");
String strPassword=sharedPreferences.getString("password", "");
String strIpAddress=sharedPreferences.getString("ip", ipAddress);
performLogin(strUsername, strPassword,strIpAddress);
}
You want to get the username and password from the shared preferences as like the ipAddress and then call the perfomLogin method.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (sharedPreferences.contains("ip")) {
performLogin(sharedPreferences.getString("username", ""), sharedPreferences.getString("password", ""), sharedPreferences.getString("ip", ""));
}

Edittext.getText().toString(); is not working android

I'm new to android developing. I started to make a login screen first but getting entered text is not working. I do not know why. I have been using log and toast but its getting here is code of mine. Toast shows empty and tag wont even appear on debug window and yes I have those fields in layout file.
public class MyActivity extends ActionBarActivity {
private static final String TAG = "LoginInfo";
EditText txtusername, txtpassword;
Button button;
String username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
txtusername = (EditText) findViewById(R.id.txtUserName);
txtpassword = (EditText) findViewById(R.id.txtPassword);
button = (Button) findViewById(R.id.btnLogin);
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), username, Toast.LENGTH_SHORT).show();
Log.d(TAG, username + password);
if ((!username.isEmpty()) & (!password.isEmpty())) {
SharedPreferences sharedpreferences = getSharedPreferences("Login_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("USERNAME", username);
editor.putString("PASSWORD", password);
editor.commit();
Log.d(TAG, username + password);
} else {
Toast.makeText(getApplicationContext(), "Entered Login Info is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});
}
You need to move
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
inside onClick() because it's value is empty. when the view is created.
change your code as below, you getText on onCreate that return blank because of no text in this.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
Toast.makeText(getApplicationContext(), username, Toast.LENGTH_SHORT).show();
Log.d(TAG, username + password);
if ((!username.isEmpty()) & (!password.isEmpty())) {
SharedPreferences sharedpreferences = getSharedPreferences("Login_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("USERNAME", username);
editor.putString("PASSWORD", password);
editor.commit();
Log.d(TAG, username + password);
} else {
Toast.makeText(getApplicationContext(), "Entered Login Info is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});
public class MyActivity extends ActionBarActivity {
private static final String TAG = "LoginInfo";
EditText txtusername, txtpassword;
Button button;
String username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
txtusername = (EditText) findViewById(R.id.txtUserName);
txtpassword = (EditText) findViewById(R.id.txtPassword);
button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
Toast.makeText(getApplicationContext(), username, Toast.LENGTH_SHORT).show();
Log.d(TAG, username + password);
if ((!username.isEmpty()) & (!password.isEmpty())) {
SharedPreferences sharedpreferences = getSharedPreferences("Login_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("USERNAME", username);
editor.putString("PASSWORD", password);
editor.commit();
Log.d(TAG, username + password);
} else {
Toast.makeText(getApplicationContext(), "Entered Login Info is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});
You should not do this in onCreate() as you call EditText.getText().toString(); when the view is created, so the user still has not entered any data. You should move them to the onClick() method.
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
These lines should not be there in onCreate(). Because initially , the EditTexts are empty.
As user gives the input, then only user would press Login Button.
So put the above mentioned lines within onClick() event of the button.
If the editTexts are found empty in onClick() event of the button , you should show the Toast message like :
"Please provide the credentials to Login!"
put these lines inside onClick()
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
Each time you enter text into edittext you can get values onClick().
Hope this help.

Categories

Resources