How to access settings (SharedPreferences?) in Android - android

I have a file res/xml/preferences.xml with these contents:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="pref_key_development_settings"
android:title="#string/pref_development_title">
<EditTextPreference
android:defaultValue="10.0.0.160/webservice"
android:key="pref_webservice"
android:summary="#string/pref_webservice_summary"
android:title="#string/pref_webservice_title" />
</PreferenceCategory>
</PreferenceScreen>
How do I access pref_webservice from an Activity?
I've tried these, and they do not work (it defaults to the second parameter as I presume it can't find the key):
SharedPreferences prefMan = getSharedPreferences("preferences", MODE_PRIVATE);
String spString = prefMan.getString("pref_webservice", "null");
SharedPreferences prefMan = PreferenceManager.getDefaultSharedPreferences(this);
String spString = prefMan.getString("pref_webservice", "null");
What am I doing wrong? Do I need to specify that preferences.xml is a shared preferences file somewhere??
EDIT
Figured it out. I was missing PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

Related

Setting sharedpreferences default value

I am using the following methods to save and read user settings:
private void saveUserSettings(){
SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userSettings.edit();
editor.putInt("timeOne",timeOne);
editor.apply();
}
private int getUserSettings(){
SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
timeOne = userSettings.getInt("timeOne",timeOne);
}
Then in onCreate the following:
SharedPreferences prefs = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
This is fine and the data is saved when the app relaunches. However I want to have default data when the app is installed initially it seems to be that the values should be stored in an xml file.
I have created the following file under res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="timeOne"
android:defaultValue="2"/>
</PreferenceScreen>
Then in onCreate:
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
I changed the "userSettings" to preferences to match up but this dosen't work and returns a value of zero. Is this method of reading the xml file ok or/and am I overlooking something?
I think you are overcomplicating yourself.
In this instruction the second parameter is the default to use if there is no shared preference with that name.
You just need to set that value to the default you need.
timeOne = userSettings.getInt("timeOne",<Put here the default value>);
EDIT I
Lets say the default value if it is the first time the app runs and there is no setting saved yet, is 2.
The method that reads the value should be like this.
private int getUserSettings(){
SharedPreferences userSettings = getSharedPreferences("userSettings", Context.MODE_PRIVATE);
timeOne = userSettings.getInt("timeOne",2);
}

Android set preferences from XML with PreferenceManager

I am trying to get preferences from XML but without using a PreferenceActivity.
I just want to load from the file when my Main activity is created and toast a value from preferences. But the problem is that the toast is empty (null?). I have a class that load the preferences.
Here is the onCreate method of the Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Preferences prefs = new Preferences();
}
Preferences class (only the constructor...)
public Preferences(Context context) {
PreferenceManager.setDefaultValues(context, "MyPrefs", 0, R.xml.preferences, false);
SharedPreferences sharedPreferences = context.getSharedPreferences("MyPrefs", 0);
Editor editor = sharedPreferences.edit();
String myValue = sharedPreferences.getString("myKey", null); // I don't know if null is OK
Toast.makeText(context.getApplicationContext(), myValue, Toast.LENGTH_SHORT).show();
}
And the XML file
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<Preference android:key="myKey" android:defaultValue="hello" />
</PreferenceScreen>
The first time I launch the app, I would like the default value to be set. So here I want the app to toast "hello" while I haven't set the value with editor.putString(key, value).
Do you know what could be wrong?
Thanks
You are programming in java. By suns convention I think you are obliged to use config.propeties file.
I will give a quick and full tutorial to get you going in this matter. I really recommend you using this method cause most of programmers do like that.
I will give you a quick tutorial how to make this file. Where to put it. And how to get data from it.
Begin.
Put a file config.properties into assets folder:
SAMPLE of config.properties
domain=#domain.com.pl
errorTextColor=\#FF0000
serverPort=1234
Method how to access and retrieve data from config.properties
public static String getConfigurationPropertiesValue(String value,
Context context) {
try {
Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("config.properties");
Properties properties = new Properties();
properties.load(inputStream);
return properties.getProperty(value);
} catch (IOException e) {
Log.e("getConfigurationPropertiesValue",
"Failed to open config property file");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Literature:
http://en.wikipedia.org/wiki/.properties
http://www.mkyong.com/java/java-properties-file-examples/
EDIT:
You can also use sharedPreferences to have more control over data like adding data/deleting data/update data. SharedPreferences are more like a SQLite database of android with a nice api to use so you don't really need to know the location of database or SQL.
In order to use it you need to create your data. You only need to do this once. Or more if user decides that he has an urge to clean you app data from settings -> applications.
Creating data:
public static void create(Context cw) {
SharedPreferences sharedPreferences = cw.getSharedPreferences(
ANDROID_MESSENGER, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isRegistered", false);
editor.putString("phoneNumber", null);
editor.putString("callingCode", null);
String uuid = UUID.randomUUID().toString();
editor.putString("token", uuid);
editor.putBoolean("internetOnly", false);
editor.putBoolean("logToDev", true);
editor.putBoolean("dataTransfer", true);
Log.i("create", "Generating Token: " + uuid);
editor.commit();
}
Accesing existing data:
public static String getToken(Context cw) {
SharedPreferences sharedPreferences = cw.getSharedPreferences(
ANDROID_MESSENGER, Activity.MODE_PRIVATE);
return sharedPreferences.getString("token", null);
}
Updating data:
public static void setPhoneNumber(Context cw, String phoneNumber) {
SharedPreferences sharedPreferences = cw.getSharedPreferences(
ANDROID_MESSENGER, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("phoneNumber", phoneNumber);
editor.commit();
}
For an mechanism that will check if data exist or if user deleted it you can use something simple like an additional variable that should be true if all your data is configured. Or there should be an checked method from appshared preferences for that.
Cheers!
I tried for a long time and found a solution for this :-)
Just a "Preference" is not being recognized by android. Though i don't know why.
If you change it as a Any of the tag like "EditTextPreference" or "CheckboxPreference" its working fine.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference android:key="CLIENT_HOMESCREEN_TITLE"
android:defaultValue="Home Screen"/>
<EditTextPreference android:key="CLIENT_ADMIN_BUTTON"
android:defaultValue="Admin"/>
<EditTextPreference android:key="CLIENT_PLAYER_BUTTON"
android:defaultValue="Player"/>
<EditTextPreference android:key="CLIENT_SAVE_BUTTON"
android:defaultValue="Save"/>
<EditTextPreference android:key="CLIENT_CANCEL_BUTTON"
android:defaultValue="Cancel"/>
<EditTextPreference android:key="CLIENT_SERVER_SETUP_IP"
android:defaultValue="IP:"/>
<EditTextPreference android:key="CLIENT_SERVER_SETUP_PORT"
android:defaultValue="Port:"/>
<EditTextPreference android:key="CLIENT_SERVER_SETUP_TITLE"
android:defaultValue="Server Setup"/>
</PreferenceScreen>

Reading shared preferences

i'm using shared preferences for the settings menu of my android app.
it's working very well but i didn't know how to use these settings on my code:
For example how to use the selected language and use it in another activity:
<PreferenceCategory
android:title="General Settings"
android:key="general_settings"
>
<ListPreference
android:key="language"
android:title="Language"
android:summary="Define the default language"
android:defaultValue="Spanish"
android:entries="#array/Languages"
android:entryValues="#array/LanguagesValues"
/>
On code behind;
SharedPreferences prefs = this.getSharedPreferences("general_settings", Context.MODE_PRIVATE);
String lanSettings = prefs.getString("language", null);
you have to set and read shared pref settings. For example:
Set:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putString("language", language);
editor.commit();
Read:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String language = settings.getString("language", "");
You could use a RadioGroup, set the Sharedpref and work with it.
Hope this help!

PreferencesScreen crashes on click

I have placed this into my PreferencesActivity
PreferencesActivity:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference preferences = findPreference("key");
preferences.setIntent(new Intent(getApplicationContext(), RegisterActivity.class));
}
preferences.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Preferences">
<Preference android:key="Pssword" android:title="Set SMS Notification Password"></Preference>
</PreferenceCategory>
</PreferenceScreen>
The moment i try to enter the preferences screen it crashes.
Your preference is called Pssword, not key.
You have a NullPointException because your key preference doesn't exist.
Replace your line Preference preferences = findPreference("key"); with Preference preferences = findPreference("Pssword");
This should resolve your issue.

Android: Can't load default values from a preferences xml file using sharedpreferences

Trying to load default values from a preference.xml file. and load them using sharedpreferences but the defaultValues from the xml file won´t load for me. Here is my code.
/res/xml/prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="prefs" android:title="prefs">
<Preference android:key="bild" android:title="bild" android:defaultValue="This is bild,0,false"/>
<Preference android:key="bild2" android:title="bild2" android:defaultValue="This is bild2,1,false"/>
<Preference android:key="bild3" android:title="bild3" android:defaultValue="This is bild3,2,false"/>
</PreferenceScreen>
And the Android code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String picture = prefs.getString("bild", "dosen't exist");
Log.e("test", "This is the picture Value: " + picture);
}
It always prints "dosent't exist", which means in this example that it isen´t loaded correctly?. And can't figure out why it does.
Any help would be appreciated, Thanks
/Eidor
According to this question, your location for a shared preferences file is wrong. Also, if I recall correctly (not feeling too well so may not remember correctly), if you want to read files with key-value pairs you are better off putting them in assets folder and reading from there.
I don't see anything wrong with the preferences being saved in prefs.xml. After recreating your code and slightly modifying it, I got to suspect the plain <Preference>-Tag instead:
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TestPreference</string>
<string name="action_settings">Settings</string>
<string name="pref_header_1">Preference Category</string>
<string name="pref_default_1">Image 1</string>
<string name="pref_default_2">Image 2</string>
<string name="pref_title_1">Title 1</string>
<string name="pref_title_2">Title 2</string>
<string name="pref_title_3">Title 3</string>
<string name="pref_key_1">pref_key_1</string>
<string name="pref_key_2">pref_key_2</string>
<string name="pref_key_3">pref_key_3</string>
<string-array name="pref_entries_3">
<item>One</item>
<item>Two</item>
<item>Five</item>
</string-array>
<string-array name="pref_values_3">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
</resources>
preference.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="#string/pref_header_1" >
<Preference
android:defaultValue="#string/pref_default_1"
android:key="#string/pref_key_1"
android:title="#string/pref_title_1" />
<EditTextPreference
android:defaultValue="#string/pref_default_2"
android:key="#string/pref_key_2"
android:title="#string/pref_title_2" />
<ListPreference
android:defaultValue="1"
android:entries="#array/pref_entries_3"
android:entryValues="#array/pref_values_3"
android:key="#string/pref_key_3"
android:negativeButtonText="#null"
android:positiveButtonText="#null"
android:title="#string/pref_title_3" />
</PreferenceCategory>
</PreferenceScreen>
MainActivity.java
private Logger log = LoggerFactory.getLogger(getClass());
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get default preferences and load default values
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
PreferenceManager.setDefaultValues(this, R.xml.preference, false);
// Check if keys exist in sharedPreferences
log.debug("Contains keys #1: {}; #2: {}; #3: {}", new Object[] {
prefs.contains(getString(R.string.pref_key_1)),
prefs.contains(getString(R.string.pref_key_2)),
prefs.contains(getString(R.string.pref_key_3))
});
// Get preferences values
String value1 = prefs.getString(getString(R.string.pref_key_1), "not found");
String value2 = prefs.getString(getString(R.string.pref_key_2), "not found");
String value3 = prefs.getString(getString(R.string.pref_key_3), "not found");
log.debug("Values #1: {}; #2: {}; #3: {}", new Object[] { value1, value2, value3 });
// prefs.edit().putString(getString(R.string.pref_key_1), getString(R.string.pref_default_1)).apply();
}
Logging result
"Contains keys #1: false; #2: true; #3: true"
"Values #1: not found; #2: Image 2; #3: 1"
Conclusion
If you want a certain preference to be user-editable, you're probably better of using a concrete Preference such as EditTextPreference, ListPreference, CheckboxPreferencete (check here for a complete list of subclasses that suits your needs.
If for some reason you still want to use plain Preferences, I suppose you have to load them manually like this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString(getString(R.string.pref_key_1), getString(R.string.pref_default_1)).apply();

Categories

Resources