get Preference by key and default value from SharedPreferences - Android Android OS

Android examples for Android OS:SharedPreferences

Description

get Preference by key and default value from SharedPreferences

Demo Code


//package com.java2s;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;

public class Main {
    private static final String PREF_NAME = "nvcclient";

    public static boolean getPreference(Context context, String key,
            boolean defaultValue) {
        SharedPreferences pref = getPreferences(context);
        return pref.getBoolean(key, defaultValue);
    }//from w ww .ja  v a 2  s  . c o m

    public static float getPreference(Context context, String key,
            float defaultValue) {
        SharedPreferences pref = getPreferences(context);
        return pref.getFloat(key, defaultValue);
    }

    public static int getPreference(Context context, String key,
            int defaultValue) {
        SharedPreferences pref = getPreferences(context);
        return pref.getInt(key, defaultValue);
    }

    public static long getPreference(Context context, String key,
            long defaultValue) {
        SharedPreferences pref = getPreferences(context);
        return pref.getLong(key, defaultValue);
    }

    public static String getPreference(Context context, String key,
            String defaultValue) {
        SharedPreferences pref = getPreferences(context);
        String value = pref.getString(key, defaultValue);
        if (value.length() == 0) {
            value = defaultValue;
        }
        return value;
    }

    public static SharedPreferences getPreferences(Context context) {
        return new ContextWrapper(context).getSharedPreferences(PREF_NAME,
                Context.MODE_PRIVATE);
    }
}

Related Tutorials