Java tutorial
//package com.java2s; //License from project: Apache License import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class Main { private static SharedPreferences sPreferences; @SuppressWarnings("unchecked") public static <T> T getPref(Context _context, String prefKey, T defValue, Class<T> clazz) { final SharedPreferences pref = getDefaultSharedPreferences(_context); if (Long.class == clazz) { return (T) (Long.valueOf(pref.getLong(prefKey, (Long) defValue))); } else if (Integer.class == clazz) { return (T) (Integer.valueOf(pref.getInt(prefKey, (Integer) defValue))); } else if (defValue instanceof String) { return (T) (pref.getString(prefKey, String.valueOf(defValue))); } else if (defValue instanceof Boolean) { return (T) (Boolean.valueOf(pref.getBoolean(prefKey, (Boolean) defValue))); } throw new UnsupportedOperationException("Class " + clazz + " not supported"); } public static SharedPreferences getDefaultSharedPreferences(Context _context) { if (sPreferences == null) { sPreferences = PreferenceManager.getDefaultSharedPreferences(_context.getApplicationContext()); } return sPreferences; } }