How to string to shared preference without an editText? - android

can I save strings to my sharedpreference without using an editText. Using an edit text this is the format of putting string to the shared preference right?
editor.putString("username", etUsername.getText().toString());
I want to happen is to get the users ID from the db for it to be saved on the sharedpreference.
editor.putString("userID", *******);
what should I put there? Thanks. I don't know how to do it.
And this is my db for the users.
myDB

editor.putString("userID", parameter);
yes, in second parameter you can save your sting whatever your want.

You're doing it right.
String stringValue = "BobSmith";
editor.putString("stringKey", stringValue);

This can be done like this:
String valueToBeSaved = etUsername.getText().toString();
editor.putString("userID", valueToBeSaved);
editor.apply();
DatabaseHelper myDatabaseHelper = new DatabaseHelper(Activity.this);
myDatabaseHelper.openDataBase();
String userId = myDatabaseHelper.getYourData(); //this is the method to query user UserId
myDatabaseHelper.close();
//now save userId in shared preferences
String valueToBeSaved = etUsername.getText().toString();
editor.putString("userID", userId);
editor.apply();
}
I hope youe are searching for this. If any doubts let me know.

Related

Not able to get String value from SharedPreferences

I save some String data to SharedPreferences but unfortunately i am unable to get the string value from sharedPreferences.
This is my code to save the data to SharedPreferences
SharedPreferences prefs = this.getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
userPhone = etPhone.getText().toString();
prefs.edit().putString("userPhone", userPhone).apply();
This saves my number perfectly but when i try to retrieve it in the next activity i get this string instead "userPhone"
This is how i retrieve the string value
String phoneNumber = prefs.getString(Config.PREF_NAME, "userPhone");
Log.i("number", phoneNumber);
My logs show phoneNumber as a string instead of the value from the user input that i saved to sharedPrefrences.
For storing values into SharedPreferences you are using Editor and method call:
prefs.edit().putString(String key, String value)
And you did it right:
prefs.edit().putString("userPhone", userPhone).apply();
For retrieving data, we are using the same key as we used for storing. In your case, it is "userPhone".
So, you should do it with:
prefs.getString("userPhone", "Some default value");
But, you mixed key with preferences name and you called
prefs.getString(Config.PREF_NAME, "userPhone");
Here is the difference.
You are actually retrieving the value from:
String phoneNumber = prefs.getString(Config.PREF_NAME, "userPhone");
But you need to do :
SharedPreferences sharedPreferences = getContext().getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
String phoneNumber = sharedPreferences.getString("userPhone", null);
It should look like this in your second Activity.
SharedPreferences prefs = this.getSharedPreferences(Config.PREF_NAME, Context.MODE_PRIVATE);
String phoneNumber = prefs.getString("userPhone", "defaultValueIfNoPhoneAvailable");
Log.i("number", phoneNumber);
The second parameter of getString is the default value in case it has no mapping for the key.

fetch integer value from sharedpreference

I use the following helper to save user input to sharedpreference:
protected void storeData(SharedPreferences.Editor editor,
String key, EditText et) {
String content = et.getText().toString();
if ("".equals(content)||" ".equals(content)) {
editor.remove(key);
} else {
editor.putString(key, content);
}
}
then
number1 = (EditText)findViewById(R.id.number1);
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
storeData(editor,"number1", number1);
editor.commit();
I wish to ask if how can I retrieve that value as a integer, then use it for some calculation.
I been searching and found this , found that they use editor.putInt(key,content);
But is that possible to extract the value as integer straight from my method?
thank you.
Your storeData() method is setting a string (putString()). Shared prefs store typed values distinctly different. That is, you cannot put "1" as a string then get it our later as an integer.
You need to use put/getInt() consistently. Alternatively you could store it as a string, and again consistently get it as a string and coerce it to an int as you need.
Your really should be using putInt(), but you can also use Integer.parseInt("some string") to convert your String value to an integer.
Use editor.commit() inside the else part
A suggestion:
use editor.apply() instead of editor.commit() as commit handles the job in foreground whereas apply handles that asynchronously.
I know, the question has been asked long time agao. I came up with similar situation. So, the might help someone in the future.
//for integer values
port = (EditText) findViewById(R.id.devicePort);
int devicePort = Integer.parseInt(port.getText().toString());
editor.putInt(getString(R.string.devicePort), devicePort);
editor.apply();

how to get the value of json object which i have saved in sharedpreference from one activity to another activity?

This is first activity through which i'm saving data in sharedpreferences...
JSONObject obj = new JSONObject(response);
public static String userid;
userid = obj.getString("userid");
String otp = obj.getString("opt");
SharedPreferences sp=getApplicationContext().getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("userid", userid);
editor.putString("opt", otp.toString());
editor.commit();
and i want the value of userid in second activity...
SharedPreferences sp = getApplicationContext().getSharedPreferences("Sharedprefs",Context.MODE_PRIVATE);
String userid = sp.getString("userid","");
String otp = sp.getString("opt", "");
i want the value of "userid" and "otp" which have been stored in "SharedPrefs" sharedprefs, and i dont want to give any default value for this....
Thanks in Advance :)
If above is your code you should change Sharedprefs in the second Preferences to SharedPrefs.
When you store data in SharedPreferences, make sure that Preference name is spelled correctly. It is case sensitive.
Find the difference between "Sharedprefs" and "SharedPrefs".
Try this way.
SharedPreferences sp = getApplicationContext().getSharedPreferences("SharedPrefs",Context.MODE_PRIVATE);
String userid = sp.getString("userid","");
String otp = sp.getString("opt", "");

How to avoid adding duplicate values in shared preferences in android?

In android, i am adding string values using shared preferences, but i want to compare the value which i am going to add to shared preferences with values which are already stored in shared preferences to avoid adding duplicate values, but i am not getting how to do this?
or is there any alternate method to avoid adding duplicate values in shared preferences?
I am adding string values using following code
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString(Name, s);
editor.commit();
In android you cannot really have duplicate value in sharedPreference because every time you change or modify a value on sharedPreference it will replace the previous with the current. So since every instance of it has a single unique key, which mean it will always be unique (in my experience every time i messed up with this keys like giving the same name key for both an Int and boolean for example i end up crashing the app or having some kind of exception)
If im wrong i hope someone else will correct me and provide you with a better answer!
I don't know whether I'm understanding your question quite well or not, but Android's SharedPreferenceshas it's own contains to check if a a key already exists or not.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(NAME)) //It already contains NAME key
On the other hand, if your worries are about a single key's value not to be repeated, just read it before storing the new value and compare themselves, no more.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.getString(NAME, "").equals(s)) {
// It does not have the same value, store 's'
sharedpreferences
.edit();
.putString(NAME, s);
.commit();
}
However, in this particular case I wouldn't perform this verification, just overwrite the value and that's it, as it always gonna be the same.
First get String value from SharedPreferences as oldvalue then compare with newvalue which you want to store. If String not match then save newvalue in SharedPreferences.
Try something like this
String str_newvalue = "new string here";
SharedPreferences sharedpref = this.getSharedPreferences(this.getPackageName(), context.MODE_PRIVATE);
String str_oldvalue = sharedpref.getString("key", "");
if (!str_newvalue.equals(str_oldvalue)) {
sharedpref.edit().putString("key", str_newvalue).commit();
}
Do this
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if(restoredText.matches(your string))
{
// do nothing
}
else
{
//save your data
}
}

regarding saving values in database in android

I am creating a sample application using shared preference.I have 3 edittext,2 Buttons,I want to save data in database of android stimulator.How can i do it.Can anybody tell me.Thanks in advance......
try something like this to store values
SharedPreferences.Editor editor = quasiprefer.edit();
editor.putString("password", "");
editor.putString("question", "");
editor.commit();
and to retrieve back values
SharedPreferences prefer = PreferenceManager.getDefaultSharedPreferences(this);
String saveQuestion = prefer .getString("question", "");
String saveAnswer = prefer .getString("answer", "");

Categories

Resources