FileStorage_SharePreference

MainActivity.java

package com.example.hd.storage_sharepreference;

import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    public static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("姓名", "韩栋");
        map.put("age", 22);
        map.put("id", 1223132123l);
        map.put("salary", 3000.0f);
        map.put("isManger", true);
        Save_SharePreference save = new Save_SharePreference(MainActivity.this);
        boolean flag = save.SaveMsg("myInformation", map);
        Log.i(TAG, flag + "");
    }

}

Save_SharePreference

package com.example.hd.storage_sharepreference;

import java.util.Map;

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

public class Save_SharePreference {
    Context context;

    public Save_SharePreference(Context context) {
        // TODO Auto-generated constructor stub
        this.context = context;
    }

    /** * @param FileName * @param map * @return */
    public boolean SaveMsg(String FileName, Map<String, Object> map) {
        boolean flag;
        String key = null;
        Object object = null;
        SharedPreferences preference = context.getSharedPreferences(FileName,
                context.MODE_PRIVATE);
        Editor editor = preference.edit();
        for (Map.Entry<String, Object> map_entry : map.entrySet()) {
            key = map_entry.getKey();
            object = map_entry.getValue();
            if (object instanceof Boolean) {
                Boolean s = (Boolean) object;
                editor.putBoolean(key, s);
            } else if (object instanceof Integer) {
                Integer i = (Integer) object;
                editor.putInt(key, i);
            } else if (object instanceof Float) {
                Float f = (Float) object;
                editor.putFloat(key, f);
            } else if (object instanceof Long) {
                Long l = (Long) object;
                editor.putLong(key, l);
            } else if (object instanceof String) {
                String s = (String) object;
                editor.putString(key, s);
            }
        }
        return editor.commit();

    }

}

你可能感兴趣的:(FileStorage_SharePreference)