How to use sharedPreference value in different classes in android - android

in main Activity i have following:
((TextView)findViewById(R.id.TextView02)).setText(getSharedPreferences("FearAlert", 1).getString("contactName", "Tap to select an Emergency Contact."));
((TextView)findViewById(R.id.TextView03)).setText(getSharedPreferences("FearAlert", 1).getString("contactNumber", ""));
now i want to use contactNumber value in ANOTHER Activty say activity2
in Activty2 is:
SmsManager.getDefault().sendTextMessage(??, null, "message",null, null, null);
return null;
what should i write in place of ?? above..help please..

In Java, there are... Never mind, In programming languages, there are variables where you can assign values to variables. like x=1; then use can use x+x=?; and will give you 2;
Here you can do
SharedPreferences sPrefs=getSharedPreferences("FearAlert", 1);
TextView tv=(TextView)findViewById(R.id.TextView02);
String YOUR_INTRESTING_STRING=sPrefs.getString("contactName", "Tap to select an Emergency Contact.");
And to pass it to the another Activity; You can put it in a Bundle
Intent i = new Intent(getApplicationContext(), YOUR_ANOTHER_ACTIVITY.class);
i.putExtra("name_of_value",YOUR_INTRESTING_STRING);
startActivity(i);
And retrive it in your AnotherActivity by
Bundle extras = getIntent().getExtras();
String value = extras.getString("name_of_value");

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity (which is not discussed here).
The context object lets you retrieve SharedPreferences through the method
Context.getSharedPreferences().
getSharedPreferences("FearAlert", 1).getString("contactNumber", "");
OR
SharedPreferences myPrefs = this.getSharedPreferences("FearAlert", 1);
String contactNumber = myPrefs.getString(contactNumber, "nothing");

you can access you preferences everywhere in your app e.g. with following method:
/**
* Get a string preference by its key from the apps preferences file
*
* #param key of preference
* #return value of preference
*/
public String getStringPreference(String key) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
return pref.getString(key, "");
}
Just set your key, e.g. "contactName" as parameter. The preferences manager requires the application context via getApplicationContext().

Assuming you have created the SharedPreferences correctly:
SharedPreferences settings = getSharedPreferences("MY_APP", MODE_PRIVATE);
You can retrieve a preference in your method by:
SmsManager.getDefault().sendTextMessage(settings.getString("contactNumber"), null, "message", null, null, null);
Assuming you've set it with the "MY_APP" shared preference tag.
settings.edit().putString("contactNumber", "XXX-XXX-XXXX").commit();

Related

How Shared Preferences in Android Works?

I came across an Android Question as follows. The result is confusing me.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putString("1", "2"); // Storing string
editor.putString("3", "4 "); // Storing string
editor.commit();
System.out.println("pref.getString() = " + pref.getString("2","3"));
Answer: pref.getString() = 3.
How does the shared preference prints this value ? Can someone please explain this ?
The first argument to get...() is the shared preferences key. The second argument is the default value to return in case there's no value by that key.
Assuming no other code has put a value with key "2" in this shared preferences file, the default value of "3" is returned when calling pref.getString("2","3").
The SharedPreference object does not print anything.
The sharedPreference stores data in key-value pairs in an xml file named MyPref in your case:
getApplicationContext().getSharedPreferences("MyPref", 0);
You put the value you want to store by calling the putXX method on the editor object obtained from the pref object by calling edit() on it:
SharedPreferences.Editor editor = pref.edit();
** putXX means put[some kind of primitive data] like int float String.
When you call putString you supply a key as the first parameter and the String value in this case as the second parameter:
editor.putString("1", "2"); // Storing string
editor.putInt("myInt", 2); // Storing integer
The commit method writes the data.
editor.commit();
The getString retrieve a string value for a key given as the first parameter and if they are no entry a default value returned which is the second parameter in this case "3":
String myValue = pref.getString("2","3")
The printing performed by calling:
System.out.println(myValue);
editor.putString("1", "2") - first argument is KEY, second argument is value.
pref.getString("2","3") - first argument is KEY, second argument is Default value (in case if such key isn't present).
In your case you've put two strings - 2 and 4 in keys 1 and 3 accordingly.
When you are trying to read string with key 2 - it is missing. So default value (3) is printed
P.s. you are using keys very similar to values - Strings containing numbers. Just put more readable keys and thing will get clearer.
Android has a page that it's very clean. Shared Preferences getString()
This method has two parameters :
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
This value may be null.
So if you have this in your SharedPreferences
editor.putString("1", "2"); // Storing string
editor.putString("3", "4 "); // Storing string
And you are doing : pref.getString("2","3")
You are looking for the SharedPreferences key with a value of "2", and if it doesn't find anything you'll get "3" as a default value.

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.

How to get values given the key value in a set in SharedPreferences in Android?

public void buttonClick(View v)
{
EditText sd = (EditText)findViewById(R.id.sd);
EditText desc = (EditText)findViewById(R.id.description);
Spinner type = (Spinner)findViewById(R.id.type);
Spinner priority = (Spinner)findViewById(R.id.priority);
Set<String> set = new HashSet();
if(!validate(sd))
sd.setError("This field cannot be empty");
else if(!validate(desc))
desc.setError("This field cannot be empty");
else
{
set.add(type.getSelectedItem().toString());
set.add(priority.getSelectedItem().toString());
set.add(desc.getText().toString());
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref",MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(sd.getText().toString(),set);
editor.commit();
Log.d("MyTag",pref.getAll().toString());
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
private boolean validate(EditText t1)
{
if(t1.getText().length()==0)
return false;
else
return true;
}
Here in the above code, I am storing the details in the SharedPreferences with StringSet. The key is sd string and the values are desc, type and `priority'. I created a Set and put the key and the corresponding values in the set. How do I fetch the values for a given key?
The method pref.getStringSet(key, Set<String>) expects both key and the values. The key value is known but what should be put in the second argument? Tried null but it expects a type of Set.
The second parameter in pref.getStringSet(key, Set<String>) is a default value in case the preference has never been set before.
Check the documentation:
Parameters
key The name of the preference to retrieve.
defValues Values to return if this preference does not exist.
So if it has already been set, the previously assigned value is returned. Otherwise defValues is returned.
You can go ahead and put null there. The following compiles and works for me:
HashSet<String> hashSet = hashSet = (HashSet<String>) sp.getStringSet("names", null);
The second value is the default value. If Lint gives you an error when you put null, just tell Lint to ignore that error.
The second argument is a default value, if the shared preference you try to get doesn't exist or, you put a wrong name as first argument it will be set to the default value passed as second argument.
The key value is a label wich you will use to get that specific shared preference, for example:
editor.putString("name_of_your_preference", value_of_preference);
and then you could retrieve that string with:
pref.getString("name_of_your_preference", default_value);
you could use NULL only as default value

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
}
}

How can I save user-created objects to storage in android?

In my app, I have flashcard objects that the user creates themselves. Users can create as many flashcards as they want, but when they exit the app and return they need to be able to see the flashcards that they previously created and be able to delete them. I have it set up so that they can create/delete, but if they exit the app they will all delete automatically. What is the best way to save the information for a flashcard? It has at least 3 strings currently, the title, the front and the back.
I looked at a few, but am not sure how I would include all three strings in the saving options that are on the android developer site.
For example shared preferences, looks like you can only save certain settings, but it allows the user to change those settings.
The internal/external storage, although very different throw up the same problem, how to have unlimited number of objects and especially how to save all three strings separately.
This is the internal storage is shown below.
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
I don't see how you can save multiple number of objects or 3 different strings.
Does anyone see a solution to my problem?
SharedPreferences seem like the simplest way for you to achieve it, and I think you've misunderstood their usage, or confused the name with a 'Preferences' screen, as you can use the SharedPreferences methods to save anything (well, any basic datatype) persistently.
For example, I use it to save my app's JSON data (which might be a decent way for you to go in terms of saving you users' flashcards in a JSONArray).
/**
* Retrieves data from sharedpreferences
* #param c the application context
* #param pref the preference to be retrieved
* #return the stored JSON-formatted String containing the data
*/
public static String getStoredJSONData(Context c, String pref) {
if (c != null) {
SharedPreferences sPrefs = c.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);
return sPrefs.getString(pref, null);
}
return null;
}
/**
* Stores the most recent data into sharedpreferences
* #param c the application context
* #param pref the preference to be stored
* #param policyData the data to be stored
*/
public static void setStoredJSONData(Context c, String pref, String policyData) {
if (c != null) {
SharedPreferences sPrefs = c.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString(pref, policyData);
editor.commit();
}
}
Where the string 'pref' is a tag used to refer to that specific piece of data, so for example: "taylor.matt.data1" would refer to a piece of data and could be used to retrieve or store it from SharedPreferences

Categories

Resources