Thursday, October 27, 2011

How to create Type for ArrayList for GSon conversions?

I love GSON, mostly because it takes away lot of time we need to spend on parsing the JSON using the native JSON libraries. Its simlple, you create a object model for the JSON and gson can covert the JSON to a well defined object instance and vice versa.
This was easy. But i got struck when i added this custom java bean to a list and the tried to convert the JSON to a list of this Java bean. GSON will not understand the type of object under the list unless we specify it. This is how its done...
1) Define a type object (type object in under the reflection package)
Type type = new TypeToken>(){}.getType();
2) Use this type as an input during converion
gson.fromJson(jsonString,type);
This will give you the arraylist with the cutom java bean inside it.

AssetManager in Android

How do you read the files kept under the asset folder in Android?
Answer is we can use Asset Manager.
1) Get all the assets using AssetManager (Under activity you have access to the get assests method)
AssetManger assets = getAssests();
2) Once you get the assets, we can look up or open the file using the file name
InputStream is = assets.open(filename);
Once you have the ionputstream, you can read the content in what ever way we need.

How to save information using Shared Preference in Android?

There are many ways to save the data in Android devices. One of them is using the shared preferences more like a key/value pair of data.

How to read the preference?
1) Get the sharedpreference for the preference name
ex) SharedPreferences prefs = ctx.getSharedPreferences(prefName,0);
2) Get all the key value pairs from the preference
ex) Map data = prefs.getAll();
3) Iterate through the map and you can retrive the data for your key.

How to Save the Preference?

1) Get the sharedpreference editor for the preference
SharedPreferences.Editor prefs =
context.getSharedPreferences(getPrefname(), 0).edit();
2) add the key and value to the preference
prefs.putString(newkey, value);

3) Commit your changes
prefs.commit();


How to remove preference?
1)Do all the above steps to get the editor and then use the remove method to remove the preference.
prefs.remove(newkey);