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();
}
Related
I've been having issues understanding how to save and read SharedPreferences. I'm trying to save four separate SharedPreferences but as I couldn't figure out how to do it, I decided to try with a simple String.
In this code I'm trying to create and save a string in SharedPreferences
Button enrollNewStudent = (Button) findViewById(R.id.enrollStudentButton) ;
enrollNewStudent.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
SharedPreferences prefs = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE).edit();
editor.putString("name", "Dave");
editor.commit();
startActivity(new Intent(MainActivity.this, AddNewStudent.class));
}
});
And in this next part I'm trying to read the SharedPreferences and have a TextView set to it in a second activity.
Context context = this;
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.testing),MODE_PRIVATE);
String toPutInTextView = sharedPref.getString(getString(R.string.testing), null);
TextView textView = findViewById(R.id.exampleTextView);
textView.setText(toPutInTextView);
When I run this app and click the button to switch to the second activity the TextView on the second activity is blank.
Does anybody see a problem with this? I've been trying to piece together what I need to do from the android developers website and from other questions here but I just cannot get this working. This is for a university project.
The problem is: sharedPref.getString(getString(R.string.testing), null) is pulling using the string getString(R.string.testing) as the key. However, the key you used when you called "putString()" was "name". So you need to use "name" as your key for your getString() call.
Try:
String toPutInTextView = sharedPref.getString("name", "<default_value>");
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), "")
Functionality Description:
Image Button(calls on a secondary application) that allow users to enter and input text, handwritten as well as keyboard input. User will then have the option to save the text. When, user exit the secondary application, the image button is supposed to displayed the saved text.
Genuine Issue:
Have intended to use shared preferences method but the saved text is still not displayed. Can anyone please help. Following is the code used.
Code:
//EDITED VERSION TO CALL OUT THE SECONDARY APPLICATION FOR USER TO INPUT TEXTandr
private void addListenerOnButtonMyScript() {
// TODO Auto-generated method stub
imageButton = (ImageButton) findViewById(R.id.imageButton_myscript);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("SingleViewActivity:onCreate:addListenerOnButtonMyScript" + ":onKey" , "Initiate myScript:");
final Intent intent = new Intent();
intent.setClassName("com.visionobjects.textwidget.sample", "com.visionobjects.textwidget.sample.SampleActivity");
startActivity(intent);
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
Log.i("Calling on Shared Preferences" , "Shared Preferences to pref_text:" + getString(R.string.pref_text) );
SharedPreferences.Editor editor = pref.edit();
editor.putString(getString(R.string.pref_text),"");
editor.commit();
}
});
}
//EDITED VERSION TO CALL ON SHARED PREFERENCES FUNCTION TO DISPLAY EDITED TEXT FROM MY_SCRIPT-20/10/2014
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();
editor.commit();
}
Strings.xml
<resources>
<string name="app_name">SalesBase</string>
<string name ="pref_text">StandardPreferences</string>
<string name="contacts_default">Contacts Details\n名字:HARRY\n公司:BARTENDER\n路名:123, Road Name\nZip:Zip\nState:State\nMobile:012-345-6789\nOffice:12-345-678\n</string>
</resources>
You are using wrong code to load the data. If loadSavedPreferences() is your final code to get data then you will not get any data. Try this
private void loadSavedPreferences(){
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
String data = prefs.getString(getString(R.string.pref_text), "");
}
However, I would suggest you to use different keys for preference name and the data you are trying to save.
SharedPreferences pref = getSharedPreferences(getString(R.string.pref_text),MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Use a different key where you are saving the data in this line and obviously value is the data you want to save. Use something like this.
editor.putString(key,value);
editor.commit();
And when you want to show the data then use the same key to get the data.
String data = prefs.getString(key, "");
Have a look at this as well.
Android Shared preferences example
I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.
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!