Friday, July 29, 2011

Sharing Objects between Activities in Android

It can be difficult and cumbersome sometimes to share arbitrary objects between Activities in Android. For primitives the best way is usually to use SharedPreferences or Intent.putExtra. 
However it is not possible to pass directly an arbitray object to an activity. A simple and effective way is to use static fields on an Application object:

public class MyApplication extends Application {

   public static MyObject myObject;

   public void onCreate() {
      //initialize myObject here, if needed

To access myObject from any Activity in the application simply with MyApplication.myObject. This approach allows clear and simple way to exchange data beween Activites.
You could also use a static hashmap, and pass the key around to access the required object.
For interprocess communication more work is required, either a ContentProvider should be used or AIDL, but the purpose of this pattern is to avoid all the boilerplate code associated with it.

Sunday, July 10, 2011

How to find available locales in Andoid

In Java the usual approach to find the available Locales on a System is to use:


This will return a pretty large number of Locales. Another approach is to use the AssetManager:


This will return the Locales that the AssetManager contains data for, which is typucally a lot less than what Locale.getAvailableLocales()
returns. It probably makes more sense only to use these Locales in an Applications.

Wednesday, July 6, 2011

Show Soft Keyboard for Text Entry

This snippet can be used to force the display of the soft keyboard

InpuptMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

However it is better to check first if the device has a hardkeyboard, in that case you might not want to show the soft keyboard.

boolean hasHardKeyboard = false;
Configuration config = getResources().getConfiguration();
if (config.keyboard != Configuration.KEYBOARD_NOKEYS) {
hasHardKeyboard = true;

Friday, July 1, 2011

Browsing the SQLite database in Android

An easy way to browse your android application database is to use the Questoid SQLite Browser for eclipse. The easiest way to install it is through the eclipse marketplace (Help > Eclipse Marketplace).

To browse the SQLite Database of an Application go to the file explorer in the DDMS perspective and look for the database file under data/data/applicationpackage/databases, select it and click on the database icon in the file browser.