set Preference by value and key to SharedPreferences - Android Android OS

Android examples for Android OS:SharedPreferences

Description

set Preference by value and key to SharedPreferences

Demo Code


//package com.java2s;

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

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

    public static void setPreference(Context context, String key,
            Object value) {//from w w  w.j  a  va2s  .  co m
        SharedPreferences pref = getPreferences(context);
        Editor editor = pref.edit();
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        } else {
            editor.putString(key, value.toString());
        }
        editor.commit();
    }

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

Related Tutorials