I am new in android development.
I've an activity in which I'm taking user name and password.and I'm passing those values to a web service which returns a key as a response.i have one toggle button in my activity. now if the user checks the toggle button that means he want to keep logged in and the user should be redirected to next activity when he next time log-in.
If toggle button is checked I'm storing user name, password and key in shared preference.
but I'm not getting how to retrieve those details next time(i.e when user next time log-in)
userDetails = this.getSharedPreferences("userdetails", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString("username", txtUname.getText().toString().trim());
edit.putString("password", txtPass.getText().toString().trim());
edit.commit();
Toast.makeText(this, "Login details are saved..", 3000).show();
this way you can fetch preference
String Uname = userDetails.getString("username", "");
String pass = userDetails.getString("password", "");
and check for login this way
if(Uname=="" && pass =="")
//Go to login
else
//Go to Next Activity
try like this
best of luck
try this for store value in sharePreferences..
SharedPreferences prefs = getSharedPreferences("Share", Context.MODE_PRIVATE );
Editor editor = prefs.edit();
editor.putInt("Value", 1 );
editor.commit();
for get value
prefs.getInt("Value",0);
/////////////////////////////////////////
String Uname = userDetails.getString("username", "");
String pass = userDetails.getString("password", "");
if(Uname=="" && pass =="")
//Go to login
else
//Go to Next Activity
Based on the Checkbox add a sharedPreferences Boolean value when the user checks/unchecks on keep logged in. Then as you call onCreate of Login activity you need to check this and call the next activity if the boolean value is true.
Avoid storing the user password.
For each user, consider storing:
the user id
a random seed unique to this user
a hash of the seeded password.
The user will need to reenter his password, then you can add the stored seed to the entered password and apply the hash algorithm X times to the seeded password. Then compare the hash to the stored hash.
Then he can encrypt the password and store it in sharedpreferences whenever he needs the password he can get that encrypted password from the sharedpreferences and decrypt it.
Try this https://prashantsolanki3.github.io/Secure-Pref-Manager/ for saving and retrieving shared preferences securely and with ease.
The keys and values are automatically encrypted.
Save:
SecurePrefManager.with(this)
.set("user_name")
.value("LoremIpsum")
.go();
Retrieve:
String userName = SecurePrefManager.with(this)
.get("user_name")
.defaultValue("unknown")
.go();
Hope this helps!
Related
*I'm new in learning android
I'm searching for any website that show on how to accept user detail for example name and age, and display it in another activity using sharedpreferences in newer version of code? Do you have any? The another activity will have a Back button pointing to the first activity. All I found was in older version and not matched in my Android Studio so, I've cancelled the program. Anyone?
In the first activity, you can save the user name and age like this:
private void saveUserInformation(String userName, int age) {
//In this activity save the name in the shared preference
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("user_name", userName).putInt("user_age", age).apply();
}
In the second activity, to get the user information, do this:
private void getUserInformation() {
//In the second activity or any other activity, you can get the userName and age like thi
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
String userName = sharedPreferences.getString("user_name", null);
int userAge = sharedPreferences.getInt("user_age", 0);
}
From your question and comment in other answers, i guess you need more explanation on how a shared preference works. When you save data in a sharedpreference, it gets saved in a file on the user device. After saving you can access that data from any activity as long as the activity has access. All you just have to do is put it in a shared preference using a unique key and get it where you need it using that same unique key. Hope it helps. If i my answer helps, don't forget to upvote. Thanks.
this is how you create a sharedpref
SharedPreferences sp=getSharedPreferences("MYPREFNAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit;
this is how you put data in it
editor.putString(key,string);
this.is how you retrieve that string back
sp.getString(key,DefaultString);
//in your first activity use
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("name","name_value").apply();
sharedPreferences.edit().putInt("age",age_value).apply();
//and now in your second activity to retrieve data
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name","");
int age =sharedPreferences.getInt("age",0);
I'm currently working on my app and I use shared preferences. The use of it works and how its applied. When it saves my info it replaces the first entered value with the second set of info. Is there a way to save multiple values in one shared preferences file?
SharedPreferences is a key-value store, similar to a Java Map object. This means that for each key you can store only one value.
One SharedPreferences file can contain many keys though.
If you are storing a limited number of items with a single key, you could do some simple serialization such as putting the values in a single comma separated String.
For more lengthy lists of information you might want to consider a SQLite database or your own file-based storage method.
If the second set of value is replacing the first set, that probably means you're saving the second set with the exact same key as the first set.
Try saving the second set of value with a different key:
editor.putString("key1", value1);
editor.putString("key2", value2);
editor.apply(); // Or commit, whichever suits your need
Update examples
int counter = 0;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// If you want to use username as key and password as value
saveUsernameAsKey();
// If you just want to use a different key everytime you click,
// you could try using a counter
// This will use key "Username0", "Username1", "Username2"...
saveUsername("Username" + counter);
counter++;
}
});
public void saveUsernameAsKey() {
userPref = getSharedPreferences("MyUsernames", Context.MODE_PRIVATE);
EditText username = (EditText) findViewById(R.id.txtEnterUserName);
EditText password = (EditText) findViewById(R.id.txtEnterPassword);
SharedPreferences.Editor editor = userPref.edit();
editor.putString(username.getText().toString(), password.getText().toString());
editor.apply();
}
public void saveUsernames(String usernameKey) {
userPref = getSharedPreferences("MyUsernames", Context.MODE_PRIVATE);
EditText username = (EditText) findViewById(R.id.txtEnterUserName);
SharedPreferences.Editor editor = userPref.edit();
editor.putString(usernameKey, username.getText().toString());
editor.apply();
}
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();
}
When I click on the 'remember me' checkbox, based on the codes it will save the username and password by sharepreferences. However, when I exit my application and go back, the username and password will disappear.
How do I save the username and password between sessions?
// Remember me function
CheckBox cbRemember = (CheckBox) findViewById(R.id.chkRememberPassword);
if (cbRemember.isChecked()) {
// save username & password
SharedPreferences mySharedPreferences = getSharedPreferences(
"PREFS", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("UserName",
String.valueOf(txtLogin.getText().toString()));
editor.putString("Password",
String.valueOf(txtPassword.getText().toString()));
editor.commit();
}
Same as you have put username and password strings inside the shared preference, you can retrieve the same by doing as below:
SharedPreferences settings = getSharedPreferences("PREFS",0);
settings.getString("UserName", "");
settings.getString("user", "");
But i think for implementing remember me functionality, just put a boolean flag whenever the login is successful:
editor.putBoolean("login",true);
and retrieve whenever app is re-started next time:
settings.getBoolean("login", false);
When you exit the app and go back, the onResume() method will be called. It's the place where you should put Paresh Mayani's codes to retrieve the username and password. Check here to understand the lifecycle of an activity in Android.
I think the problem is with the Activity.MODE_PRIVATE flag use instead getSharedPreferences("PREFS", MODE_WORLD_WRITEABLE) flag.
I'm new to android development
In my application I want to keep log-in status of user in my activity. I have 2 edit boxes for entering name and password. And 1 check-box for user if he wants to keep log-in.
When user clicks on login button I'm saving name and password in shared preference. And in onCreate method I want to retrieve that value. If user has clicks check-box then he should directly redirect to next page. But its not working.
Here is my code:
signUpButton=(Button)findViewById(R.id.signUpLoginId);
signUpButton.setOnClickListener(this);
//toggleButtonOnOff=(ToggleButton)findViewById(R.id.togglebutton);
loginEditText = (EditText) findViewById(R.id.loginNameID);
passwordEditText=(EditText)findViewById(R.id.passwordId);
box=(CheckBox)findViewById(R.id.checkbox);
preferences=PreferenceManager.getDefaultSharedPreferences(context);
String n=preferences.getString(PREF_USERNAME, null);
String p=preferences.getString(PREF_PASSWORD, null);
loginEditText.setText(n1);
passwordEditText.setText(p1);
Intent intent1=new Intent(LoginActivity.this,FindFishMenuActivity.class);
startActivity(intent1);
LoginActivity.this.finish();
if(box.isChecked())
{
box.setChecked(true);
Toast.makeText(LoginActivity.this,"box value set to true",Toast.LENGTH_LONG).show();
password=passwordEditText.getText().toString();
preferences=context.getSharedPreferences(key_str, MODE_PRIVATE);
editor=preferences.edit();
editor.putString(PREF_USERNAME, name);
editor.putString(PREF_PASSWORD, password);
editor.commit();
intent=new Intent(LoginActivity.this,FindFishMenuActivity.class);
startActivity(intent);
LoginActivity.this.finish();
}
If you finish your Activity, the Code after it is never reached!
But I would put the code which saves your Name and Password to the SharedPreference before you fire the Intent. Maybe the Preference-Object isn't saved yet when you try to read from it in the other Activity. Try debuging this using LogCat.