save User Data to SharedPreferences - Android android.content

Android examples for android.content:SharedPreferences

Description

save User Data to SharedPreferences

Demo Code


//package com.java2s;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class Main {
    /**//w  w  w  . j a va  2 s  .  co m
     * 
     * @param context
     * @param fileName
     * @param mode
     * @param map
     */
    public static void saveUserData(Context context, String fileName,
            int mode, Map<String, Object> map) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                fileName, mode);
        Editor edit = sharedPreferences.edit();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof String) {
                edit.putString(key, value.toString());
            } else if (value instanceof Integer) {
                edit.putInt(key, (Integer) value);
            } else if (value instanceof Boolean) {
                edit.putBoolean(key, (Boolean) value);
            } else if (value instanceof Float) {
                edit.putFloat(key, (Float) value);
            } else if (value instanceof Long) {
                edit.putLong(key, (Long) value);
            }
        }
        edit.commit();
    }
}

Related Tutorials