Tuesday, July 3, 2012

Mobile Apps: Saving user preferences (Titanium only)

I am passionate about mobile apps and one of my favorite mobile app development toolkit is Titanium by Appcelerator.

Often mobile apps need to save user preferences such as font size and such. As I dug around, I found some interesting posts and built upon them, I figured it may be worth sharing it. So, here is one way of storing user preferences using Properties

1 2 3 4 5 6 7 8 9 10 
//Created for http://www.blog.iSl8.com

//This code checks to see if there is a user preference set, otherwise, it sets the default preference property.
if (Titanium.App.Properties.getString('MyCustomPreference1') != null){
Ti.API.info('Custom Preference 1 was already set to ' + Titanium.App.Properties.getString('MyCustomPreference1'));
}
else { //Set default Custom Preference 1
Ti.App.Properties.setString('MyCustomPreference1', 'Default Preference1 value');
Ti.API.info('The Custom Preference 1 was defaulted to : ' + Titanium.App.Properties.getString('MyCustomPreference1'));
}

Then, where ever I needed to access it, I just used the getString method.

Why not use Global variables instead?
When I initially started, I thought that is what I should do. Save or default it to a property, and the first time my code accesses this property, just copy it into a Global variable, which can be referenced in any file across the App.

For some reason, the getString code seems cleaner (as in more explicit) to me. That way, if someone changes this property using the setString method, they know exactly what they are changing, instead of some proxy Global variable.

Also, I am not a JavaScript Guru, but I would imagine that setting a property is internally just doing that anyway.

Happy Coding!