get User Data from SharedPreferences - Android android.content

Android examples for android.content:SharedPreferences

Description

get User Data from SharedPreferences

Demo Code


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

public class Main {

    public static Object getUserData(Context context, String fileName,
            int mode, String key) {
        Object object = null;//from   ww w .  j ava 2 s.  com
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                fileName, mode);
        if (sharedPreferences != null) {
            Map<String, ?> map = sharedPreferences.getAll();
            if (map.size() > 0) {
                for (int i = 0; i < map.size(); i++) {
                    Object value = map.get(key);
                    if (value instanceof String) {
                        object = sharedPreferences.getString(key, "");
                    } else if (value instanceof Boolean) {
                        object = sharedPreferences.getBoolean(key, false);
                    } else if (value instanceof Float) {
                        object = sharedPreferences.getFloat(key, 0);
                    } else if (value instanceof Long) {
                        object = sharedPreferences.getLong(key, 0);
                    } else if (value instanceof Integer) {
                        object = sharedPreferences.getInt(key, 0);
                    }
                }
            }
        }
        return object;
    }
}

Related Tutorials