Android set preferences from XML with PreferenceManager - android

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>

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 SharedPreferences update does not work

I know, this issue has been dealt with in many threads, but I cannot figure out this one.
So I set a shared preference like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.apply();
I read the preferences like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = null;
spinnerValuesSet = prefs.getStringSet(spinnerName,null );
Everything works, except for my changes are visible while this activity runs i.e. - I display the values from the SharedPreferences, allow the user to delete or add and then update the ListView. This works, but after I restart the application, I get the initial values.
This for example is my method to delete one value from the list, update the values in SharedPreferences and update the ListView
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
for (String s : spinnerValuesSet)
{
if(s == currentSelectedItemString)
{
spinnerValuesSet.remove(s);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, spinnerValuesSet );
editor.apply();
break;
}
}
updateListValues();
}
});
And this is the method that updates the ListView:
private void updateListValues()
{
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
if(spinnerValuesSet.size() > 0)
{
names = new ArrayList<String>();
names.clear();
int k=0;
for (String s : spinnerValuesSet) {
names.add(k, s);
k++;
}
namesAA = new ArrayAdapter<String> ( this, android.R.layout.simple_list_item_activated_1, names );
myList.setAdapter(namesAA);
}
}
Any help is much appreciated.
The Objects returned by the various get methods of SharedPreferences should be treated as immutable. See SharedPreferences Class Overview for reference.
You must call remove(String) through the SharedPreferences.Editor returned by SharedPreferences.edit() rather than directly on the Set returned by SharedPreferences.getStringSet(String, Set<String>).
You will need to construct a new Set of Strings containing the updated content each time since you have to remove the Set entry from SharedPreferences when you want to update its content.
Problem happens because the Set returned by SharedPreference is immutable. https://code.google.com/p/android/issues/detail?id=27801
I solved this by created a new instance of Set and storing in all the values returned from SharedPreferences.
//Set<String> address_ids = ids from Shared Preferences...
//Create a new instance and store everything there.
Set<String> all_address_ids = new HashSet<String>();
all_address_ids.addAll(address_ids);
Now use the new instance to push the update back to SharedPreferences
I may be wrong but I think the way you are retrieving the Shared Preferences is the problem. Try using
SharedPreferences prefs = getSharedPreferences("appPreferenceKey", Context.Mode_Private);
Use editor.commit(); instead of editor.apply();
Example Code:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.commit();
I hope this helps.
Depending on the OS Build you may have to save values in a different way.
boolean apply = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
public static void saveValue(SharedPreferences.Editor editor)
{
if(apply) {
editor.apply();
} else {
editor.commit();
}
}

Shared preferences only saved first time

The program creates preferences the first time but after that it never changes them. I would appreciate assistance in understanding why.
This is the PreferencesScreen where the xml is called.
public class PreferencesScreen extends PreferenceFragment{
private final String TAG = "PreferencesScreen";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate");
addPreferencesFromResource(R.xml.prefs);
}
In the preferences I have a ListPreference and a Preference which calls an activity to store emails.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Information Collected">
<ListPreference
android:key="loggins"
android:title="Logs Stored"
android:summary="Choose the top kind of logs do you want to store."
android:dialogTitle="Choose Logs"
android:entries="#array/logs"
android:entryValues="#array/logsValues"/>
</PreferenceCategory>
<PreferenceCategory android:title="Email Configurations">
<Preference
android:key="pushing"
android:title="The Email Activity"
android:summary="Just push">
<intent android:action = "ADDING_EMAIL"/>
</Preference>
</PreferenceCategory>
</PreferenceScreen>
Everything until here. The problems are in the activity called...
public class AddingEmail extends ListActivity implements OnClickListener{
private Set<String> emails;
private EditText emailAdd;
SharedPreferences.Editor editor;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.addingemail);
Button add = (Button) findViewById(R.id.add);
emailAdd = (EditText) findViewById(R.id.email);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = prefs.edit();
prefList = toArrayList(prefs.getStringSet("emailWrongs", null));
add.setOnClickListener(this);
}
public void onClick(View v) {
Set<String> list = prefs.getStringSet("emailWrongs", null);
String newEmail = emailAdd.getText().toString();
if (list==null){ //first time the preferences are called.
emails = new TreeSet<String>();
editor.putStringSet("emailWrongs", emails);
editor.apply();
}
if (newEmail != ""){
emails=prefs.getStringSet("emailWrongs", null);
emails.add(newEmail);
editor.putStringSet("emailWrongs", emails);
editor.apply();
}
}
}
The point is that it always stores the first time well but if I when I add another email the preferences doesnt't change. They looks like they change because if I printed them they show all the emails I add but the preference file doesn't change (Checking it in the File Explorer). And if i reboot or close and open again, the preferences are only with the first email I add.
The thing is if i back to and change the preference of the ListPreference, then it stores all the changes even the emails I added.
Hope I was clear, it has a lot of code because i wanted to be very explicit.
Thank you for the help.
After more than a week looking for the mistake I found it.
I think this can be helpful for a lot of people who had the same trouble.
The problem was that when I call the preferences to get the String Set, it only reference the list and not make a copy of it. So I have to create a new list and add all the elements stored before and also add the new element and then with the editor change the preferences with the new list.
The code is like this:
Set<String> list = prefs.getStringSet("emailWrongs", null);
Set<String> newList = new TreeSet<String>();
String newEmail = emailAdd.getText().toString();
if (newEmail != ""){
if (list != null){
for(String each: list){
newList.add(each);
}
}
newList.add(newEmail);
editor.putStringSet("emailWrongs", newList);
editor.apply();
}
For storing a Stringset, a better way to do this is to first remove the last SharedPreferences value, then save the new one with the same key. Like this:
defaultSharedPreferences.edit().remove("keysValue").commit();
defaultSharedPreferences.edit().putStringSet("keysValue",likesset).commit();

Android: updating displayed preferences from SharedPreferences

I'm writing an android app with a preferencesActivity in which selections made in my instance of preferencesActivity affect the values of other preferences items displayed. While I'm able to change the values of the underlying SharedPreferences items pogrammatically, those changed values aren't reflected in the displayed list items until I exit my preferencesActivity and reload it. Below is a stripped down version of my settings class and xml file which illustrate the problem. If a user sets Guitar as the value for the preference with the key instrumentList, I'd like the preference with key tuningChoice to revert to Standard.
//necessary import declarations go here
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
Log.d("onSharedPreferencesChanged", "sharedPreferences changed. key: " + key);
Editor preferencesMod = sharedPreferences.edit();
String instrumentChoice = sharedPreferences.getString("instrumentList", "Guitar");
if(key.equals("instrumentList")) {
Log.d("Settings", "key is instrumentList. chooseTuning before if: " + sharedPreferences.getString("chooseTuning", "no luck"));
if(instrumentChoice.equals("Guitar")) {
preferencesMod.putString("chooseTuning", "Standard");
preferencesMod.commit();
Log.d("Settings", "chooseTuning after if: " + sharedPreferences.getString("chooseTuning", "ciao"));
}
}
}
}
xml file preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings">
<ListPreference android:title="Choose an Instrument" android:key="instrumentList" android:entryValues="#array/instruments" android:entries="#array/instruments"/>
<ListPreference android:title="Choose Tuning" android:key="chooseTuning" android:entryValues="#array/tuningChoices" android:entries="#array/tuningChoices" android:persistent="true"/>
</PreferenceScreen>
I can call addPreferencesFromResource again in my onSharedPreferenceChanged method and that loads a duplicate of all the preferences items, displayed below the old items, with the correct values. If I could figure out some way to cancel out the initial addPreferencesFromResource called during onCreate, I guess I would be set.
Any help would be appreciated, Thanks
I do something along these lines...hopefully it helps:
ListPreference list = (ListPreference) getPreferenceManager().findPreference("myList");
list.setValue(sharedPrefs.getString("myList", "default"));
list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
sharedPrefs.put("myList", newValue.toString());
return true;
}
});
You need to prevent addPReferencesFromResource from running twice? Is this loading your default values? If so, add an additional SharedPreference called DEFAULTS_LOADED and read its value in on create like: (WARNING PSUEDO CODE):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean loadDefaults = app_preferences.getBoolean(DEFAULTS_LOADED, true);
if(loadDefaults)
{
addPreferencesFromResource(R.xml.preferences);
Editor editor = app_preferences.edit();
editor.putBoolean(DEFAULTS_LOADED, true);
editor.commit();
}
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
This will prevent you defaults from being written to the shared preferences every time your activity starts. I assume this is at least a portion of your issue.
If anyone comes to this problem, this is the solution:
ListView list = preferenceActivity.getListView();
list.performItemClick(list, 1, list.getItemIdAtPosition(1));
Maybe I am too late for answering this. But, I hope this might help beginner like me.
PackageInfo packageInfo = null;
try {
packageInfo = preference.getContext().getPackageManager().getPackageInfo(preference.getContext().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
preference.setSummary(packageInfo.versionName);

Android ==> Preference?

my app crashes with a null pointer exception on the code below.
i have an xml preference file under res/xml/defaults.xml
Any idea why it's crashing?
public class Preference extends Activity {
public Preference()
{
}
public String getPreference(String key)
{
//it still crashes here
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String result = settings.getString(key, null);
return result;
}
}
Preference files are not storead in project's /res/xml/defaults.xml
They are stored on the device in your application folder something like
/data/data/com.your.pkg/default.prefs
Try do not specify the file name, as you will have some problems with the preference files, like this OP had here
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Then you will probably have to query
preferences.getString('weightPref', null);
Here's a sample code which shows how to save and retrieve Preferences. Here I am saving username and password in SharedPreferences.
SharedPreferences uPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor; = uPreferences.edit(); //Instantiating editor object
protected void storeSharedPrefs(String username, String password) {
/*
* Storing in Shared Preferences
*/
editor.putString("username", username);
editor.putString("password", password);
editor.commit(); //Commiting changes
}
Retrieving username and password in another activity from SharedPreferences.
private SharedPreferences mSP;
mSP = getSharedPreferences("CurrentUser", MODE_PRIVATE);
String username = mSP.getString("username", null);
String password = mSP.getString("password", null);
Hope it helps..
Setting a value in the shared preferences:
Editor prefs = getSharedPreferences("Application_name", MODE_PRIVATE).edit();
prefs.putString("key", accountKey);
prefs.commit();
Getting the value from another activity:
String accountKey =
this.getSharedPreferences("Application_name", MODE_PRIVATE).
getString("key", null);
It would be nice if you access the variable by using some predefined handler, such as getString(R.string._key), instead of the hardcoded string "key".
Your Preferences should extend PreferenceActivity. Then you need to create a resource xml file for preferences, and reference that in your PreferenceActivity like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
etc.
}
The preferences xml should have a PreferenceScreen as the top level element, and you can take advantage of all the different preference views Android makes available to you for setting preferences. This would be the most common, and elegant way to do it.

Categories

Resources