How to display the value of a SharedPreference without entering the dialog - android

I have some Shared Preferences in my application defined in an XML file. They are EditTextPreferences. I want to display the existing values on the Preference screen so that the user doesn't have to enter the Preference Edit Dialog to see the current value of the Preference. The defaultValue is only visible in the Dialog screen. I want to see the defaultValue in the main preferences screen - maybe in the place of android:summary. How can I do this?
<EditTextPreference
android:key="PREF_LT_500"
android:title="Step 1"
android:summary="I dont want a summary - I want to show current value"
android:inputType="numberDecimal"
android:defaultValue="0.8952"
android:dialogTitle="Enter Blah " />
Thanks in advance

You could try:
yourPrefrence.getText();
Or a more generic solution:
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
String ans = p.getString(keyStr, defaultValue);
When this is a Context, keyStr is the key & defaultValue is a default value in case the key is not found (usually "")

Related

Change string value using putBoolean return a numeric value in android?

I have string field <string name="categegoriesStatus">true</string>
Now inside settingsActivity I am changing its value on preference click.
final SharedPreferences sharedpreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(getResources().getString(R.string.categegoriesStatus), false );
editor.apply();
But it is not changing it to false, but change it to some numeric value. And I don't get my desired result.
You have a string, but you want to save a boolean. Then, you should be this:
boolean result = getResources().getString(R.string.categegoriesStatus).equals("true");
editor.putBoolean(result, false );
Good luck!
You are using Sharedpreferences wrongly.
in the statement editor.putBoolean(getResources().getString(R.string.categegoriesStatus), false );
you are inserting editor.putBoolean("true", false); which is not what you are expecting it to do.
Information stored in shared preferences should be in key value format.
Read the android documentation from this link: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
Shared Preferences only saves/retrieve key value pairs. It does not change your string resource values. Once you have declared a string resource field, you cannot change it's value at runtime. Please refer to this answer.

What is the name of SharedPreferences file name?

I am new to Android and I am kind of stuck for 6 hours straight.
The problem is I don't know the name of the preferences file, and I need to get values from preferences file. I am using Android Studio and created a "Settings Activity". All the way I had not given name to any file except SettingsActivity.java.
So my question is what is the name of the Shared Preferences file (cause the application is keeping the values). Or otherwise if there is a way to find out.
Or perhaps I am missing something obvious in code. Following is my relevant code.
String key = "example_text";
final String PREF_FILE_NAME = "SettingsActivity";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
String value = preferences.getString(key, " null");
EDIT 1: I have an activity named RemoteDevice.java, within this activity I have a Async Task subclass for internet usage. Now I have stored IP address through the above mentioned PreferencesActivity and now want to retrieve it. But am unable to find it.
EDIT 2: In the following code I am trying to get value from edit text.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:key="example_text"
android:title="#string/pref_host_ip_address"
android:defaultValue="#string/pref_default_host_address"
android:selectAllOnFocus="true"
android:inputType="numberDecimal"
android:digits="123456789."
android:capitalize="words"
android:singleLine="true"
android:maxLines="1" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:key="example_list"
android:title="#string/pref_title_add_friends_to_messages"
android:defaultValue="-1"
android:entries="#array/pref_example_list_titles"
android:entryValues="#array/pref_example_list_values"
android:negativeButtonText="#null"
android:positiveButtonText="#null" />
And I am guessing here android:key is the key to be passed as arguments in
String value = preferences.getString(key, " null");
I am using Android Studio and created a "Settings Activity".
Then you get your SharedPreferences via PreferenceManager.getDefaultSharedPreferences(). Replace:
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
with:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
You can use this:
String key = "example_text";
final String PREF_FILE_NAME = "SettingsActivity";
shared = getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
String value = preferences.getString(key, " null");
But first you have to save some value with your key like:
shared.edit().putString(key,"MY_VALUE").commit();
Run your project on a real device and if a SharedPreferences file (it has .xml extension) is created you can find it in the root catalog of the device, here to be more exact:
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
or
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
By the way, you may just use getPreferences() method. Change your
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
into
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
Your SharedPreferences file will get a default name. But keep in mind that it is worth using getPreferences() instead of getSharedPreferences() only if you won't need more than one SharedPreferences file in your project.

How to get preferences values Android

I have a preferences screen in Android with multiple , like PreferenceCategory and EditTextPreference. But how do I access these fields? I searched on Google and came across findPreference, which is deprecated I guess. So how can I find these fields in my MainActivity.class so I can use their values or make onclick events for them.
Thanks in advance.
You can use the code below as an example
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
String strUserName = SP.getString("username", "NA");
boolean bAppUpdates = SP.getBoolean("applicationUpdates",false);
String downloadType = SP.getString("downloadType","1");
Note that the first parameter is the key and the second parameter is the default value to return in case the value is not present.
use shared preferences instead
http://developer.android.com/reference/android/content/SharedPreferences.html

Multi language settings and getting string array item - android

I want to make my app settings with multi language support. Value of settings item will be different in each language. I have string array:
<string-array name="syncTemperature">
<item>#string/celcius</item>
<item>#string/fehrenheit</item>
</string-array>
Which is used in:
<ListPreference
android:key="prefTempUnit"
android:entries="#array/syncTemperature"
android:summary="#string/pref_temp_current"
android:entryValues="#array/syncTemperature"
android:title="#string/pref_temperature" />
and when I will call:
String celcius = sharedPrefs.getString("prefTempUnit", "Celcius")
I will get different value everytime.
My question is how to have one value for all strings under one item.
For example when I want to check what user choose and make some action after.
Like this:
if(prefTemUnit==celcius){
setTempUnitToCelc();
}
EDIT:
For now I figured out one option:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String unit=sharedPrefs.getString("prefTempUnit", "Celcius");
String[] stringArray = getResources().getStringArray(R.array.syncTemperature);
if(unit.equals(stringArray[0])){
//mymethod
}
but I dont know if its the proper one.
Okay I got your solution:
First of all:
String celcius = sharedPrefs.getString("prefTempUnit", "Celcius") will return "Celcius" as a default value. Maybe you should remove it?
Second:
If you would like to access the String value according to the actual language, you should use:
String retrievedValueFromStringXML = getResources().getString(R.string.celcius);
To add:
ListPreference has a method called getValue(), you should use it as well to retrieve the actual value.

How to make read only (programmatically filled) Preferences?

How to make Preferences items with programmatically filled values (like: Version, Model number...)?
Why not use android.preference.Preference directly?
<Preference
android:key="version"
android:title="#string/version" />
No edit dialog, no more attribute, and information only!!
//Set the version string in your code
findPreference("version").setSummary(version);
I accomplished this with the following:
In my application_preferences.xml I have the following preference. This makes it so it is still black (not gray), but still cannot be edited by the user. Making it gray makes it difficult to read.
<EditTextPreference
android:key="version"
android:title="#string/version"
android:enabled="false"
android:selectable="false"
android:persistent="false"
android:shouldDisableView="false"/>
In the preference activity onCreate method, get the version preference and set the title to the application version.
EditTextPreference versionPref = (EditTextPreference)findPreference("version");
String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
versionPref.setTitle(getString(R.string.version) + ": " + version);
You can set the preferences within you code, and check if it already is filled before you fill it. As long as you do not give users access to change this information, all they can do is "clear local data", which will cause the program to re-fill the data if you do it right.
I use this technique to store unique IDs for the device, who is logged in, etc. The user doesn't even (and should never) know what I keep track of, all they know is they have a smooth program that does what they need it to do.
Example:
SharedPreferences settings = context.getSharedPreferences("preferanceName", 0);
SharedPreferences.Editor editor = settings.edit();
int value = foo;
editor.putInt("ValueToStore", value);
editor.commit();
Kevin Westwood it is perfect thanks!!
In my case I just change the setTitle to setSummary, so the value is visible bellow the title.
String serverUrl = "http://...";
EditTextPreference pref = (EditTextPreference)findPreference("serverPrefKey");
pref.setSummary(serverUrl);

Categories

Resources