Android getSharedPreferences NullPointerException

If your application doesn’t have an activity, or you need to read/write from/to the preferences file, you might have a hard time dealing with the getSharedPreferences API.

To overcome this (but for other advantages as well), it makes sense to subclass the Application, and create an extended Singleton class – defined as a class whose number of instances that can be instantiated is limited to one. Thus, at any given time only one instance can exist, no more.

The mechanism is as follows:
1. Create a subclass of Application, and define one static object inside the class:
Singleton.java:

public class Singleton extends Application {
	private static 		Singleton				m_Instance;
...

2. Set the android:name attribute of your tag in the AndroidManifest.xml to point this singleton class:
AndroidManifest.xml


...

3. Define the Singleton mechanism , and initiate the sharedPrefenreces as static object:

public static String 	PREFS_NAME 	   = Singleton.PRJNAME + "_PREFS";
public static 		SharedPreferences prefs	= null;
public Singleton() {
	super();
	Log.e(LOG_TAG, "Singleton created.");
	m_Instance = this;
	//	
}
// Double-checked singleton fetching
public static Singleton getInstance() {
	// init instance 
	if(m_Instance == null) {
		synchronized(Singleton.class) {
			if(m_Instance == null) new Singleton();
		}
	}
	if (prefs == null) prefs = m_Instance.getSharedPreferences(PREFS_NAME, 0);
		
	return m_Instance;
}

Now you can successfully use the prefs object to access the application preferences.

Another advantage of using the Singleton, is for storing application global variables, that in this case will survive the various application cycles (unlike those defined in your Activity, etc).

To use the Singleton, do the following:
Singleton.getInstance().

Leave a Reply