android 本地数据存贮之sharedpreference

sharedpreference简介

  • sharedpreferece 采用xml文件格式存贮
  • sharedpreference 在手机中位置是 /data/data/项目主包名/shared_prefs/ 下面
  • 建议用真机调试程序时,手机root过 ,可以装个Root Explorer软件 ,这个软件比较方便。sharedpreference相对比较简单,读写,可以封装个工具类使用。

以下是我自己封装的 SharedpreferenceUtil 操作类

public class SharedpreferenceUtil {

/**
 * 根据target 和 keys得到结果集
 * @param application
 * @param fromTarget
 * @param keys
 * @return
 */
public ArrayList<String> read(Application application,
        String fromTarget, ArrayList<String> keys) {

    SharedPreferences preference = 
            application.getSharedPreferences(fromTarget, Context.MODE_PRIVATE);
    ArrayList<String> resList = new ArrayList<String>();
    for(int i=0;i<keys.size();i++) {
        String resTmp = preference.getString(keys.get(i),"");
        resList.add(resTmp);
    }
    return resList;
}

/**
 * sharedpreference 写入数据
 * @param application
 * @param totarget
 * @param map 
 */
public void write(Application application,
        String totarget,HashMap<String,String> map) {
    SharedPreferences preference = 
            application.getSharedPreferences(totarget,Context.MODE_PRIVATE);
    Editor editor = preference.edit();

    Iterator<Entry<String, String>> iter = map.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<String,String> entry = iter.next();
        String key = entry.getKey().toString();
        String val = entry.getValue().toString();
        editor.putString(key,val);
    }
    editor.commit();
}

}

具体调用时的读入写出

SharedpreferenceUtil sharedpreferenceUtil = new SharedpreferenceUtil();

HashMap< String , String> map = new HashMap< String, String>() ;
map.put(“count”, “1”);
sharedpreferenceUtil.write(getApplication(), “loginCount”, map);

ArrayList keys = new ArrayList();
keys.add(“count”);
ArrayList arrayList = new ArrayList();
arrayList = sharedpreferenceUtil.read(getApplication(), “loginCount”, keys);

使用时需要注意 sharedpreference 与 sqlite , 文件等方式存贮的不同,多调试,查看。

你可能感兴趣的:(android,数据存储)