Check if key exists in Shared Preferences - android

I'm creating Shared Preferences as follows
preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();
String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();
editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);
and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.
I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.

Try contains(String key) Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if
the preference exists in the preferences, otherwise false.

Every method for fetching values from SharedPreferences has default value which is returned in case the key does not exist
preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
// the key does not exist
} else {
// handle the value
}

Try out
SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
String strPref = shf.getString("SERVERIP", null);
if(strPref != null) {
// do some thing
}

I know this is a late answer but for those who want to know if a shared preference is either empty or zero size, you can check it two ways.
preferences = getSharedPreferences("text", 0);
Map<String, ?> entries = preferences.getAll();//get all entries from shared preference
Set<String> keys = entries.keySet();//set all key entries into an array of string type
//first option
if(keys.isEmpty()){
//do your staff here
}
//second option
if(keys.size()==0){
//this shows that it is empty as well
//do your staff here
}
//Below is extra
//If you want to get the names of each keys also, you can use
//For each loop as well
//Go through the set of keys
for (String key : keys) {
String keyName = key;//get each key name
}

LoadRuns();
if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
Toast.LENGTH_SHORT).show();
}
loadedruns++;
SaveRuns("runs", loadedruns);
public void SaveRuns(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadRuns(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);
}

Related

How i will get multiple data from shared preference?

I have saved multiple data using shared preference. I want to read multiple data from shared preference. I have tried but can not success. I can read one data but unable to read multiple data.Thanks.
//Save multiple data
private static int incrementedValue = 0;
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String id = idEditText.getText().toString();
String name = nameEditText.getText().toString();
SharedPreferences.Editor editor = faves.edit();
editor.putString("favourite" + incrementedValue, id + "::" + name + ",");
editor.commit();
Toast toast = Toast.makeText(MainActivity.this, "saved!", Toast.LENGTH_SHORT);
toast.show();
incrementedValue++;
}
})
Here is read data from shared preference code.
//Show multiple data
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String id = faves.getString("favourite", "");
String name = faves.getString("favourite","");
textShow.setText(id+" "+name);
Toast.makeText(MainActivity.this,"Show!",Toast.LENGTH_LONG).show();
}
});
You have made the key as "favourite" + incrementedValue and accessing the value with the key "favourite" which are not the same, and it looks like you have saved both the values id and name in a single String which is again inappropriate, so change your code like this,
SharedPreferences.Editor editor = faves.edit();
editor.putString("favourite id" + incrementedValue, id);
editor.putString("favourite name" + incrementedValue, name);
editor.commit();
and access data like this,
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String id = faves.getString("favourite id"+INCREMENT_VALUE_COUNT, "");
String name = faves.getString("favourite name"+INCREMENT_VALUE_COUNT,"");
You have to replace INCREMENT_VALUE_COUNT with the position number you want to get data of.
You can add multiple data in SharedPreferences
SharedPreferences.Editor editor = faves.edit();
editor.putString("id", id);
editor.putString("name", name);
editor.commit()
You could get the value by
String id = (faves.getString("id", "0"));
String name = (faves.getString("name", ""));
As Here you are adding value separated by :: and ,.
You should get
String favourite = faves.getString("favourite", "");
And split favourite by , and get separated values and after that split by ::

Why sharedpreference value not getting in when retrieving?

I aaded three shared preferences as below code. And I am able to retrieve onl n shared preference value.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("Loggedin",true);
editor.putString("userId",userid);
editor.putString("pwd",password);
editor.apply();
editor.commit();
I used the following code for retrieving from another activity. I am able to retrieve only the boolean value. Other values are not there. getting the default value for the string values. please help me.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "0");
String pwd=preferences.getString("pwd", "0");
check first the value u store in preferences are stored or not
using this code
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", null);
String pwd=preferences.getString("pwd", null);
if(userId==null || pwd==null)
{
//data not therer
}
else
{
//do something with data
}
and let me know if any error occured..
I think you're not getting the SharedPreferences in a correct way.
See the doc for ex: https://developer.android.com/training/basics/data-storage/shared-preferences.html
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
Also, you don't need to call apply() AND commit(). Just one of those is enough. See the javadoc for the differences btw them.
Use this code
String userId=preferences.getString("userId", null);
String pwd=preferences.getString("pwd", null);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "");
String pwd=preferences.getString("pwd", "");
if(userId==null || userId==""||pwd==null ||pwd=="")
{
}
else
{
}
Try code in this way.
Set values in First Activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("Loggedin",true);
editor.putString("userId",userid);
editor.putString("pwd",password);
editor.apply();
Retrieve value in Second Activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "");
String pwd=preferences.getString("pwd", "");
Used in that way for retrieve values from shared preferences for your code.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
//Checking the value of userId and pwd,if they are null then there is no values of userId and pwd other than default.
if (userId != null && pwd != null) {
String userId = preferences.getString("userId", "0");
String pwd = preferences.getString("pwd", "0");
} else {
String userId = "0";
String pwd = "0";
}

Using Shared Preferences for High Score saving

Hell I am trying to make highscore for my project but my code is only saving last value not highest value
How can I store only highest value? here is my code .
This is saving process ->
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
TextView outputView = (TextView)findViewById(R.id.textscore);
CharSequence textData = outputView.getText();
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
This is Reading process
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
String textData = prefs.getString(TEXT_DATA_KEY, "No Preferences!");
TextView outputView = (TextView) findViewById(R.id.textread);
You need to check the previously saved value to see which is highest else it you will just save the latest value, not the highest
E.g.
if (textData != null) {
int score = Integer.parseInt(textData.toString());
if(score > prefs.getInt(TEXT_DATA_KEY, 0)) // Or get String, with parse Int.
{
//editor.putString(TEXT_DATA_KEY, textData.toString()); // Should be saved as int
editor.putInt(TEXT_DATA_KEY, score);
editor.commit();
}
}
You need to store a new value only if the existing value in shared preferences is lesser than the new value.
You don't seem to be having this value check in your code
Replace
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
with
if (textData != null) {
if(Integer.parseInt(prefs.getString(TEXT_DATA_KEY, "0")) < Integer.parseInt(outputView.getText())) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
}
First of all why are you saving high scrore as string, use int or float (if you must).
The simplest way is to read high score before saving it and compare to the one you try to save.
You'll want to keep track of your in-game high score. That's easiest done using a number rather than using a text view's string:
int hiScore = 0;
In your startup, perhaps in onCreate(), you'll want to obtain the previous high score:
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
try {
hiScore = prefs.getInt(HI_SCORE, 0);
} catch (NumberFormatException e) {
hiScore = 0;
}
When a new score is obtained, you'll want to record it if it's higher than the previous high score:
if (newScore > hiScore) {
hiScore = newScore;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HI_SCORE, hiScore);
editor.commit();
}

Android: String and a shared Preference string not matching

I am grabbing a String from text file on a url and saving it to sharedPreferences ... then the next time it grabs the String, it compares it against the old one stored in shared preference and if its different it notifies the user.
I am getting the string from url fine and its saving in sharedPreferences, but when I try to compare them with an if (x == y) statement it always results as not the same;
Here is the onPostExecute()
protected void onPostExecute(String result) {
String Input;
String oldInput;
Input = result.toString();
oldInput = currentSavedSettings();
if (Input == oldInput){
Toast.makeText(MainActivity.this, "fixed", Toast.LENGTH_LONG).show();
} else {
savePrefs("CURRENT_SETTINGS_FILE", Input);
//the toasts were used to ensure that neither were returning null
Toast.makeText(MainActivity.this, oldInput, Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, Input, Toast.LENGTH_LONG).show();
// the following is commented out until I fix this issue
//createNotification();
}
}
and the currentSavedSettings which is getting the old CURRENT_SETTINGS_FILE
private String currentSavedSettings() {
SharedPreferences sp =
PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String result = sp.getString("CURRENT_SETTINGS_FILE", null);
return result;
}
and for good measure here is what i am using to save the SharedPreference
private void savePrefs(String key, String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
Use .equals or .equalsIgnoreCase to compare strings.
For more info
How do I compare strings in Java?
Did you try this,
passcode == pref_passcode // is not the same according to Java
String passcode;
pref_passcode.contentEquals(passcode); //try this or
pref_passcode.equals(passcode)
You should always use one of these to compare string. do not use equal signs (==)

How to save value in SharedPeference in the actitvity and access it all other classes

I want to save totalBalance in this activity to SharedPreferances and the retrive it in another class.
so i want totalbalance to be displayed in another activities in same application...
if possible also edit it in other activites...
please help... thanks
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
// Genrating random number Random number
Random rn = new Random();
randomNumber = (int) rn.nextInt(9) + 1;
// changes textView1 equals to random number
textView1.setText("Random Number is "
+ Integer.toString(randomNumber));
button1.setText("Play Again");
// Matching random number to ArrayList
if (positive_IDs.contains(randomNumber)) {
// if matched then changes textView2 to Matched Number
textView2.setText("Number: "
+ Integer.toString(randomNumber) + " Matched");
totalBalance = totalBalance + winingPrize;
textView5.setText("Total Balance = Rs: "
+ String.format("%.2f", totalBalance));
}
}
try this,
public void saveValue(String lock, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("Value", lock);
editor.commit();
}
public String getValue(Context context) {
SharedPreferences savedvalue = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedvalue.getString("Value", "");
}
Save Value as Following
int Value;
private void saveValues(){
SharedPreferences readSP = getSharedPreferences("String", MODE_PRIVATE);
SharedPreferences.Editor editor = readSP.edit();
editor.putString("String", Value);
editor.commit();
}
Retrive value in any of your Class As following
int value;
private void getSavedValue()
{
SharedPreferences settings = getSharedPreferences("String", MODE_PRIVATE);
value=settings.getString("String", "");
}
// try this
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("balance", String.format("%.2f", totalBalance));
editor.commit();
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
String total = sharedPreferences.getString("balance");
Use following code to retrive your value from SharedPreference,write this in other class where you want to retrive value of total balance
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
Editor edit1 = remembermepref.edit();
edit1.putInt("totalbalance_key",totalBalance);
edit1.commit();
and to store total balance into ShardPreference use in your activity:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int totalbalance = pref.getInt("totalbalance_key");
Now use totalbalance way you want.
Most important thing is to check whether you have used same key to restore as well as tostore the value in SharedPreference
Hope this helps..

Categories

Resources