SharedPreferences保存的数据主要是类似于配置信息格式的数据,因此它保存的数据主要是简单类型的key-value对。
我写了个类,直接拿来存储数据和读取数据的。
package com.jinbi.app.service;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PerferencesService {
public Context context;
public SharedPreferences preferences;
public PerferencesService(Context context){
this.context = context;
preferences = context.getSharedPreferences("jinbi", Context.MODE_PRIVATE);
}
/**保存参数
* @param key 键值
* @param value 值
*/
public void save(String key,String value){
Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit(); //必须要提交一下
}
public void save(String key,Float value){
Editor editor = preferences.edit();
editor.putFloat(key, value);
editor.commit();
}
public void save(String key,boolean value){
Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
/**获取参数
* @param key 键值
* @return
*/
public Map<String,String> getPreferencesStringMap(String key){
Map<String,String> params = new HashMap<String,String>();
params.put(key, preferences.getString(key, ""));
return params;
}
public float getPreferencesFloat(String key){
return preferences.getFloat(key, (float) 0.0);
}
public boolean getPreferencesBoolean(String key) {
// TODO Auto-generated method stub
return preferences.getBoolean(key, false);
}
}