Android – Parcel data to pass between Activities using Parcelable classes

Passing data between activities on android is unfortunately, not as simple as passing in parameters. What we need to to do is tag these onto the intent. If the information we need to pass across is a simple object like a String or Integer, this is easy enough.

String strinParam = "String Parameter";
Integer intParam = 5;

Intent i = new Intent(this, MyActivity.class);
i.putExtra("", stringParam);
i.putExtra("", intParam);


Passing in custom objects is a little more complicated. You could just mark the class as Serializable
and let Java take care of this. However, on the android, there is a serious performance hit that comes with using Serializable. The solution is to use Parcelable.

Continue reading

Android – Managing Global Configuration

The Problem

Accessing preferences / configuration / settings from Android is actually pretty straightforward as long as you are in an Activity. To read:

// PREFS_FILENAME = "nameOfPrefsFile";

SharedPreferences pref = getSharedPreferences(PREFS_FILENAME,

String string = pref.getString("key", "default");
// 1 is the default if key isn't set
int intValue = pref.getInt("intKey", 1); 

// and so on

SharedPreferences is the key class. To write, you also need the SharedPreferences.Editor class, as follows:

// PREFS_FILENAME = "nameOfPrefsFile";
SharedPreferences pref = getSharedPreferences(PREFS_FILENAME,
Editor editor = pref.edit();
editor.putString("key", "value");
editor.putInt("intKey", 5);  

// Until you call commit, the changes will not
// be written, so don't forget this step

In general however, you will need access to settings in more than one activity and it seems a bit wasteful to get these bits littered through the application. Since I am lazy and like to write things just once, I  separated all the prefs stuff into one class called Settings.

Continue reading