Thursday, August 13, 2009

Notes on Android SDK:PreferenceActivity, XML Preferences and using them

Okay so today I was trying to get preferences to work with my app. Now for those of us who have developed on iPhone we are aware that we can setup a plist for settings that will be show up in the settings application on the iphone. This is find and dandy but do we want our users to have to go to the settings application only to change a few settings in our app. No of course.

Well the android has a similiar functionality, that creates a setting page quickly. The beauty of it is that you can load it into your app quite easily. There is some documentation on this widely available, the following website provides a great tutorial on setting up the ui.

http://androidguys.com
the article in question is What's Your Preference in three parts.

The one thing that it doesn't cover is how to use the application settings throughout the app. Anyway asuming you are using the above tutorial to set up user preferences.

the folllowing line of code will recover the settings.


SharedPreferences mprefs = PreferenceManager.getDefaultSharedPreferences(this);

and then you can read them like so.

CharSequence[] names = getResources().getTextArray(R.array.questiontypes);
for(int i=0; i
Log.v(TAG, mprefs.getBoolean(names[i].toString(), true) + "");
}

if you want to alter them from somewhere other than the settings page. you need
a SharedPreferences.editor from the above. Then just do some thing like the following.

meditprefs.putInt(key,value);
meditprefs.commit()
//the above is very important it savs until this line is called and changes are ignored
its like
[[NSUserDefaults standardUserDefaults] synchronize];



No comments:

Post a Comment