Integer Shared preference allways returns 0 - android

I am trying to code a simple password check for protecting the settings of my app. The password should be saved in a shared preference. The main calls the setPassword when the sharedPreference returns zero. This is to make sure that there will be a password set, when somebody tries to enter the settings the first time. The setPassword should then set a password and safe it in the sharedPreference. But when checking if there was a password set, the sharedPreference allways returnes 0.
this is my main:
final Intent intentSetPasswords = new Intent(this, SetPasswordActivity.class);
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
passwordToCheck = sharedPreferences.getInt("PASSWORDSETTINGS", 0);
//setting button on click listener
buttonSetings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//check if a password was set muss Überarbeitet werden
passwordToCheck = sharedPreferences.getInt("PASSWORDSETTINGS", 0);
Log.e("password", ""+ passwordToCheck);
if(passwordToCheck==0){
startActivity(intentSetPasswords);
}else{
startActivity(new Intent(MainActivity.this, PasswordCheckActivity.class));
}
}
});
and tis is my setPassword:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_password);
final Intent intentSettings = new Intent(this, SettingsActivity.class);
buttonSetPassword = (Button)findViewById(R.id.buttonSetPassword);
textViewSetPassword = (TextView)findViewById(R.id.textViewSetPasswordText);
editTextPassword = (EditText)findViewById(R.id.passwordNumericSettingsSetPassword);
final Intent intent = new Intent(this, MainActivity.class);
buttonSetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counterButton++;
switch (counterButton){
case 1:
password = editTextPassword.getText().toString();
if (password.length() == 4){
Log.d("First Password", "taken");
buttonSetPassword.setText("Confirm Password!");
editTextPassword.setText("");
}else{
Log.d("First Password", "not taken");
textViewSetPassword.setText("The Password must be\nfour numbers long!");
password = "";
editTextPassword.setText("");
counterButton=0;
}
break;
case 2:
passwordToConfirm = editTextPassword.getText().toString();
if (Integer.parseInt(passwordToConfirm) == Integer.parseInt(password)){
Log.e("password", password);
Log.e("passwordToConfirm", passwordToConfirm);
SharedPreferences sharedPreferences = getSharedPreferences("PASSWORDS", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("PASSWORDSETTINGS", Integer.parseInt(password));
editor.commit();
startActivity(intentSettings);
finish();
}else{
textViewSetPassword.setText("The passwords aren't the same!\nTry again!");
buttonSetPassword.setText("Set Password");
editTextPassword.setText("");
passwordToConfirm = "";
password = "";
counterButton = 0;
startActivity(intent);
}
break;
}
}
});
}
I guess there is a problem with the sharedPreference, but I don't get what.

Easily use the library below to manage data
https://github.com/orhanobut/hawk

Firstly, check counterButton value and ensure case 2 branch is executed.
Secondly the sharedPreferences for setting and the sharedPreferences for getting should be same. you could do like this:
private final static String MyPREFERENCES = "MyPrefs"; //define two class fields
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);//in activity Oncreate() methods.
//and set or get in other place as you want.

First you get sharedpreferences like this
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Later when setting the password you get it as below
SharedPreferences sharedPreferences = getSharedPreferences("PASSWORDS", 0);
They're two different sharedpreferences. Use the first sharedpreferences.
For more info refer to this page https://developer.android.com/training/data-storage/shared-preferences

Related

How to create multiple users registration and login activity in an android?

I've made registration and login activity in an android using shared preferences. User is able to registered and logged in successfully. But my problem is when new user is registered, it delete the previous user's registration details.
Here is my registration page:
public class Registration extends Activity implements
View.OnClickListener
{
SharedPreferences pref;
Editor editor;
TextView btn_registration , btn_formlogin;
EditText et_name, et_pass, et_email , et_phone ;
ImageView btn_upload ;
private static final int PICK_IMAGE_REQUEST = 0;
private Uri mImageUri;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
et_name = (EditText) findViewById(R.id.edt_Name);
et_pass = (EditText) findViewById(R.id.edt_userPassword);
et_email = (EditText) findViewById(R.id.edt_userEmail);
et_phone = (EditText) findViewById(R.id.edt_Phone);
btn_registration = (TextView) findViewById(R.id.btn_registration);
btn_formlogin = (TextView) findViewById(R.id.btn_formlogin);
btn_upload = (ImageView)findViewById(R.id.img_upload);
Map<String,String> values = new HashMap<String,String>();
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
btn_upload.setOnClickListener(this);
SharedPreferences preference =
PreferenceManager.getDefaultSharedPreferences(this);
final String mImageUri = preference.getString("image", null);
btn_upload.setImageResource(R.drawable.adduser);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is
private mode
pref = getSharedPreferences("USER_CREDENTIALS", 0);
// get editor to edit in file
editor = pref.edit();
// the tap of button we will fetch the information from four edittext
btn_registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
boolean validName = true;
boolean validPass = true;
boolean validPhone = true;
boolean validEmail = true;
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String pass = et_pass.getText().toString();
String phone = et_phone.getText().toString();
if (isEmpty(et_name)) {
et_name.setError("Enter the Name");
validName = false;
}
if (isEmpty(et_pass)) {
et_pass.setError("Password can't be null");
validPass = false;
}
if (isEmail(et_email) == false) {
et_email.setError("Enter valid email");
validEmail = false;
}
if (isValidMobile(et_phone) == false) {
validPhone = false;
}
final String required_email= pref.getString("Email",null);
final String required_phone=pref.getString("Phone",null);
if(et_email.equals(required_email)){
validEmail = true;
}
else if(et_phone.equals(required_phone)){
validPhone = true;
}
if (validName && validPass && validPhone && validEmail){
// as now we have information in string. Lets stored them
with the help of editor
editor.putString("Name" , name );
editor.putString("Email", email);
editor.putString("Password", pass);
editor.putString("Phone", phone);
editor.putString("image", String.valueOf(mImageUri));
editor.commit(); // commit the values
Toast.makeText(Registration.this, "Registration
Successful", Toast.LENGTH_LONG).show();
session = new SessionManager(getApplicationContext());
session.createLoginSession(name, email, mImageUri);
// after saving the value open next activity
Intent ob = new Intent(Registration.this,
DashBoard.class);
startActivity(ob);
}
else{
Toast.makeText(Registration.this, "Registration
unsuccessful! Please retry.", Toast.LENGTH_LONG).show();
}
}
});
I just want to know how to register multiple user using shared preferences file ?
If you will have multiple users, it is better to use a database(sqlite) than a shared preferences.
in shared preference you can save only single value in a object if you want to save multiple users in your device then you can use room database to store multiple user details in your device. Shared Preference can be used only for single information or if you want to store multiple values in shared preference then you can store arrayList in shared prefefrence.
save array list in shared preference:-
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getCamEval(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("sdk_camEval", null);
}
public static void setCamEval(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("sdk_camEval", set);
mPrefsEditor.commit();
}

Issues with implementing the login using shared preference

I have mentioned my complete code for the login and logout process to my application. Sometimes this code works but sometimes it just allows me to go to menu activity even without login. FYI: this code really worked earlier once i wanted to implement the remember me option, then only all these issues came up. can anyone check this and find me my issue or suggest me if u got any proper code for this process. when i logout and and open the application sometimes i can see the menu.
I have used shared preference and not using sessions for login and logout. is it correct. Im bit confused i would really appreciate any help. thanx in advance.
login code
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
EditText emailET;
EditText pwdET;
String email;
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String email = emailET.getText().toString();
String password = pwdET.getText().toString();
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Login process started...",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),
"Login error, invalid email",
Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(
getApplicationContext(),
"Login error, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
final TextView textView = (TextView) findViewById(R.id.link_to_landing);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
finish();
return false;
}
return super.onKeyDown(keyCode, event);
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
}
}
logout code
final RelativeLayout relativeLayout3 = (RelativeLayout) rootView
.findViewById(R.id.logoutlistview);
relativeLayout3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences pref = getActivity().getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null ) {
Editor editor = pref.edit();
editor.clear();
editor.commit();
email = "";
password = "";
firstname = "";
lastname = "";
// show login form
Intent intent = new Intent(getActivity(),
LActivity.class);
startActivity(intent);
intent.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
}
}
});
use this method to create a sharedPreference and then access it with this same name from any where in any activity within the same app
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
Editor e = sp.edit();
e.put(key,value);
e.commit();
and when getting the same sharedPreference in another activity use this method
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
sp.get(key,value);
Please check the below link which might help you.
http://androidapplicationdeveloper.weebly.com/login-and-logout-useing-sharedprefrences.html
In your code you have didn't set values of sharedpreference to blank while logout.
Hope it will help you.

set and store password in android apps

I have try to set and store the password for my apps, but it is not working at all. The password should be setted first time then return the home page, then when the user open it again the password should be stored but somehow it didn't store it.
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences passfile = getSharedPreferences("ans",0);
String pass = passfile.getString("ans", null);
check.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String answer1 = answer.getText().toString();
//Check that user typed in an answer
if(answer1.length()<8){
Toast.makeText(CheckPwActivity.this, "Answer must be 8 characters long", Toast.LENGTH_SHORT).show();
answer.setText("");
answer.requestFocus();
return;
}
answer.getEditableText().toString();
//check if the answer is valid
if (answer1.equals("ans")) {
Intent intent2 = new Intent(CheckPwActivity.this,MainActivity.class);
startActivity(intent2);
}else{
return;
}
}});
}
public void setPassword(String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
Editor preferenceEditor = context.getSharedPreferences("password", 8).edit();
preferenceEditor.putString(key, value);
preferenceEditor.commit();
}
public static String getPassword(String filename) {
return context.getSharedPreferences("password", 2).getString(filename,"");
}
you are using shared preferences wrong, in your set password you get shared preferences but then you get it again but in a different context
this is all you need to use shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
then when you want to set it you use the editor you just got
editor.putString(key,pass).commit;
then to get it from shared preferences you would just do
preferences.getString(key,defaultString);

android - sharedpreferences return null value

I'm trying to use sharedpreferences to check whether the user logged in before they start using the app. I save the username in shredpreferences when user log in.
Login.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button btnLogin = (Button) findViewById(R.id.buttonlogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View adapt) {
EditText usernameEditText = (EditText) findViewById(R.id.EditUserName);
userName = usernameEditText.getText().toString();
EditText passwordEditText = (EditText) findViewById(R.id.EditPassword);
userPassword = passwordEditText.getText().toString();
if (userName.matches("") && userPassword.matches("")) {
toast("Please enter Username and Password");
return;
} else if (userName.matches("") || userName.equals("")) {
toast("Please enter Username");
return;
} else if (userPassword.matches("") || userPassword.equals("")) {
toast("Please enter Password");
return;
} else {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", userName);
editor.commit();
new DownloadFilesTask().execute();
}
}
});
}
private void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
}
protected void onPostExecute(Void result) {
toast("user logged in");
startActivity(new Intent(Login.this, MainActivity.class));
finish();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
}
}
and I tried to check the username value before I start my mainactivity.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String username =sharedPreferences.getString("MEM1", "");
if(username.equalsIgnoreCase("")||username.length()==0)
{
toast("username is null");
startActivity(new Intent(MainActivity.this, Login.class));
finish();
}
but the username is always null. Please help. Thanks
Calling getPreferences means that you have to be in the same activity. Using getSharedPreferences allows you to share the preferences between activities. You just have to define a name for the preferences when calling getSharedPreferences("Pref name here", MODE_PRIVATE);
Write below Code instead of your code to save username into sharedpreferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("MEM1", userName);
editor.commit();
And Use below code For Get Preferences Value.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("MEM1","");
private final String TAXI_SPREF = "TAXI_SHARED_PREFERENCES";
//set-save data to shared preferences
SharedPreferences.Editor sPEditor = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).edit();
sPEditor.putInt("USERID", etUserID.getText().toString());
sPEditor.putString("EMAIL", etEmail.getText().toString());
sPEditor.apply();
//get data from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE);
int userID = sharedPreferences.getInt("USERID", 0);
string email = sharedPreferences.getString("EMAIL", 0);
//////// or /////
String email = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).getString("EMAIL","EMPTY");
if (!email.equals("EMPTY")){
etEmail.setText(email);
}

How to use remember me function in my android login application

I am using the code for remember my username and password. i have tried a lot of hours for the code for remember my username name and password but i cant success in it.
Here is my code which i have download from internet but it didn't work for me.
I have declared this variable in the extends activity.
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS_PASS = "prefsPassword";
after that I have also declare different variable like below.
public String PREFS_USERS;
public String PREFS_PASS;
String username;
String upass;
and in the click listener i have given the following code.
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
username = etUsername.getText().toString();
upass = etPassword.getText().toString();
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_USERS, username)
.putString(PREFS_PASS, upass)
.commit();
and at the time at retry i have return the following code in the oncreate activity to retry my user name and password.
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USERS, "");
upass = pref.getString(PREFS_PASS, "");
But when I run the application i cant get the username and password.First time when i load the application i checked the remember me check box after log in and log out back from the application and close the application and when come back to it.it was not saved for me.
The problem is in declaring the variables
you have declared
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS_PASS = "prefsPassword";
public String PREFS_USERS;
public String PREFS_PASS; //assigned null here
.putString(PREFS_PASS, upass) //here value of PREFS_PASS is null
Use the following code
better do like the folowing
public String PREFS_USERNAME= "prefsUsername";
public String PREFS_PASSWORD="prefsPassword";
Store the data as using following code
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
passwordInString = password.getText().toString();
userNameInString = username.getText().toString();
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_USERNAME, userNameInString)
.putString(PREFS_PASSWORD, passwordInString)
.commit();
retrieve the data like the following
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String usernameName = pref.getString(PREFS_USERNAME, "");
String upassWord = pref.getString(PREFS_PASSWORD, "");
Thanks
Deepak
It should look something like this (obviously you can use global vars so you dont have to specify them in several places):
String PREFS = "MyPrefs";
SharedPreferences mPrefs;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPrefs = getSharedPreferences(PREFS, 0);
//check if the remember option has been check before
boolean rememberMe = mPrefs.getBoolean("rememberMe", false);
if(rememberMe == true){
//get previously stored login details
String login = mPrefs.getString("login", null);
String upass = mPrefs.getString("password", null);
if(login != null && pass != null){
//fill input boxes with stored login and pass
EditText loginEbx = (EditText)findViewById(R.id.login_box);
EditText passEbx = (EditText)findViewById(R.id.pass_box);
loginEbx.setText(login);
passEbx.setText(upass);
//set the check box to 'checked'
CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.remeber_cbx);
rememberMeCbx.setChecked(true);
}
}
}
private void saveLoginDetails(){
//fill input boxes with stored login and pass
EditText loginEbx = (EditText)findViewById(R.id.login_box);
EditText passEbx = (EditText)findViewById(R.id.pass_box);
String login = loginEbx.getText().toString();
String upass = passEbx.getText().toString();
Editor e = mPrefs.edit();
e.putBoolean("rememberMe", true);
e.putString("login", login);
e.putString("password", upass);
e.commit();
}
private void removeLoginDetails(){
Editor e = mPrefs.edit();
e.putBoolean("rememberMe", false);
e.remove("login");
e.remove("password");
e.commit();
}
You would probably call the saveLoginDetails() & removeLoginDetails() methods in the OnClick listener:
CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.remeber_cbx);
boolean isChecked = rememberMeCbx.isChecked();
if(isChecked){
saveLoginDetails();
}else{
removeLoginDetails();
}
I hope you can find it useful
U can do this.. create a boolean variable with default value "false" and set a boolean value to true when user choses for rememberMe and put an if condition before validating user password and other stuff.. and use the boolean value in this condition..
SharedPreferences myPrefs;
onCreate()
{
myPrefs=this.getSharedPreferences("PREF_NAME",Context.MODE_PRIVATE);
if(myPrefs.getBoolean("firstTime", false))
{
startActivity(new Intent(this,SeeRecordsActivity.class));
finish();
}
}
on signIn button:
boolean c=chkbox.isChecked();
if(c==true)
{
SharedPreferences.Editor editor=myPrefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}

Categories

Resources