Android not getting saved sharedPreference value into my edittext - android

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);
}

Related

Not able to clear shared preferences

I made a simple login activity in which I used android sqlite database to store login information i.e. username and password. When user click create account button in signup activity, s/he will be transferred to another activity where they can see what is their username and pass. In that screen I need to check if preferences are clear and then the text of the button will be changed based on the decision.
I passed the info between activities using SharedPreference, but I can not delete it or clear it when the user clicks sign out.. Below is the code of both activities..
Here's my SignUp.java
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
tv=(TextView)findViewById(R.id.textView);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
if(password.length()<8) {
Toast.makeText(getApplicationContext(),"Password must be 8 digits longer",Toast.LENGTH_LONG).show();
}
else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
try {
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name,userName);
editor.putString(Pass,password);
editor.commit();
} catch (NullPointerException e) {
e.printStackTrace();
}
intent=new Intent(getApplicationContext(),AfterLogin.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
loginDataBaseAdapter.close();
}
And the AfterLogin.Java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.afterlogin);
username=(TextView)findViewById(R.id.Username);
name=(TextView)findViewById(R.id.Name);
user=(TextView)findViewById(R.id.User);
pass=(TextView)findViewById(R.id.Pass);
sout=(Button)findViewById(R.id.SignOut);
s= sharedPreferences.getString(Name,"");
us=sharedPreferences.getString(Pass,"");
username.setText(s);
name.setText(s);
user.setText(s);
pass.setText(us);
sout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.clear();
editor.commit();
String n=sharedPreferences.getString(Name,"");
if (n == null) {
sout.setText("Signed Out");
}
}
});
}
AfterLogin.java you have checked
n == null
but passed the default value as empty for String n
String n=sharedPreferences.getString(Name,""); //EMPTY
change
if (n==null) {
sout.setText("Signed Out");
}
to
if (n.isEmpty()) {
sout.setText("Signed Out");
}
Can you try by committing the clear and commit in a single line. Like editor.clear().commit() or editor.clear().apply(). This might help you since you are committing or applying changes on editor object after making changes.
The problem could be that you are using String n=sharedPreferences.getString(Name,""); which always returns something. Default value if preference doesn't exists or it's value if it exists.
To check if a preference has been deleted i'd better use String n=sharedPreferences.contains(Name); which returns a boolean that shows if the preference exists or not.
Hope it helps!

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();
}

Unable to access a string from SharedPreferences in Android

So I have two screens, a set password screen and an enter password (login) screen. I'd like it to pop up the enter password screen if there is no password (ie, the application's never been used) and upon subsequent launches go to the login screen. If the user enters a password, it compares with the value stored in sharepreferences and continues to the menu if it's correct. But the login screen seems unable to access the password after the set-password screen is used.
How do I make the login screen see the password set by the registration page?
Here's the create password code:
public class CreatePassword extends Activity {
public EditText setPass1, setPass2;
String newPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createpassword);
setPass1 = (EditText)findViewById(R.id.editTextSetPassword);
setPass2 = (EditText)findViewById(R.id.editTextRepeatSetPassword);
}
public void btnSubmitNewPassword(View v){
if(setPass1.getText().toString() != "") {
if (setPass1.getText().toString().equals(setPass2.getText().toString())) {
newPass = setPass1.getText().toString();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putString("password", newPass);
prefEditor.apply();
Toast.makeText(getApplicationContext(), newPass, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "New Password Set", Toast.LENGTH_LONG).show();
startActivity(new Intent(CreatePassword.this, Menu.class));
} else {
Toast.makeText(getApplicationContext(), "Passwords don't match!", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), "Please Enter Desired Password", Toast.LENGTH_LONG).show();
}
}
}//end CreatePassword class
And the EnterPassword (login) screen that refuses to use the password just set:
public class EnterPassword extends Activity {
EditText editTextPasswordAttempt;
SharedPreferences sharedPref;
String passwordAttempt, passwordActual;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enterpassword);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean passwordExists = sharedPref.contains("password");
if(passwordExists == false){
startActivity(new Intent(EnterPassword.this, CreatePassword.class));
}
editTextPasswordAttempt = (EditText)findViewById(R.id.editTextPassword);
}
public void btnSubmitToMenu(View v){
passwordActual = sharedPref.getString("password", );
Toast.makeText(getApplicationContext(), passwordActual, Toast.LENGTH_LONG).show();
passwordAttempt = editTextPasswordAttempt.getText().toString();
if(passwordAttempt.equals(passwordActual)) {
startActivity(new Intent(EnterPassword.this, Menu.class));
}
else{
Toast.makeText(getApplicationContext(), "Invalid Password", Toast.LENGTH_LONG).show();
}
}
}
You are using 2 different SharedPreferences.
In CreatePassword activity you do:
getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
But in EnterPassword activity you do:
PreferenceManager.getDefaultSharedPreferences(this);
If you use the same line in both Activities it should work.
You need to use same name of SharedPreferences while access SharedPreferences values.Access SharedPreferences in EnterPassword activity with same way using below line:
getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);

Password stored in SharedPreferences not working in 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();

Deny activity access on user login

I would like to deny access to an activity, say the user profile edit activity, if the user has not yet logged in with a REST request to the server.
For now, after the user has successfully logged in he is stored locally on the phone preferences.
protected void onPostExecute(ResponseEntity<User> responseEntity) {
HttpHeaders headers = responseEntity.getHeaders();
if (null != headers) {
List<String> values = headers.get(Constants.LOGGED_IN_USER_AUTH_TOKEN);
if (null != values && values.size() > 0) {
String token = values.get(0);
if (null != token) {
loginActivity.storeUser(responseEntity.getBody(), token);
}
}
}
}
public void storeUser(User user, String token) {
if (null != user) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString(Constants.LOGGED_IN_USER_EMAIL, user.getEmail());
editor.putString(Constants.LOGGED_IN_USER_JWT, token);
editor.apply();
Intent intent = new Intent(getApplicationContext(), UserProfileActivity.class);
startActivity(intent);
}
}
I wonder how to deny access to the profile edit activity.
Here is how I retrieve the stored email address from the preferences:
private boolean getProfile() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String email = settings.getString(Constants.LOGGED_IN_USER_EMAIL, null);
String token = settings.getString(Constants.LOGGED_IN_USER_JWT, null);
new UserProfileAsyncTask(this, email, token).execute();
return false;
}
Any hints on strategy to adopt are welcome.
Inside the onCreate() method of your Profile Edit activity, check to see if the user is logged in. If the user is not logged in then simply redirect them back to the Login activity using an Intent.

Categories

Resources