Tuesday, 27 August 2013

Saving and retrieving long values from Shared preferences

The shared preferences of Android could be used to save simple data, such as String, Integer or Long. When the user retrieves the saved data, it allow she to set an default value which is returned if the data is not found. As personal preferences I like to set the default value as null, so I can be sure that the data is not saved.

Here is the problem, for the Long value, there is a conversion called unboxing. In order to return the default value, it unboxes the default value from Long to long. If the default value is null, it will throw a NullPointerException, which is not desired.

in order to return a null pointer when the data is not found, before try to get the data, the shared preferences must be checked.

SharedPreferences sharedPreferences = context.getSharedPreferences("myFile", Context.MODE_PRIVATE);

// It doesn't matter what value has been set, it will neve be used
public static final Long DEFAULT_LONG = Long.valueOf(-1);

// Long
public Long getLong(LongId longId) {
if (sharedPreferences.contains(longId.toString())) {
return sharedPreferences.getLong(longId.toString(), DEFAULT_LONG);
} else {
return null;

Note that the another option is catch the nullPointerException and return null instead, but since it happens even when there are data saved, the method will return null ALWAYS, so it cannot be used.

StackOverFlow - unboxing null-Object to long results in NullPonterException, fine?
JavaDoc - Chapter 5. Conversions and Promotions

Further information:
Onkar Joshi's Blog - Java NullPointerException ninja - 10 facts you need to know to avoid problem with null

No comments:

Post a Comment