1.sharedPreferences中文件的存储格式是xml文件格式
2.新增加的相同键名的记录会覆盖原来的同键名的记录
3.可以存储json格式的数据
一、sharedPreferences封装好的操作代码:
package com.example.text;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class FileDB {
private SharedPreferences m_preferences;
private Editor m_editor;
public FileDB() {
super();
}
public boolean setTable(Context context_in, String strTableName) {
if (strTableName == null) {
return false;
}
m_preferences = context_in.getSharedPreferences(strTableName,Context.MODE_PRIVATE);
m_editor = m_preferences.edit();
return true;
}
public void put(String strAttributeName, String strValue) {
m_editor.putString(strAttributeName, strValue);
m_editor.commit();
}
public String get(String strAttributeName) {
return new String (m_preferences.getString(strAttributeName, "NULL"));
}
}
activity中调用示例:
//建表
fileDB.setTable(MainActivity.this,"user");
//存数据
fileDB.put("name", "zhangsan");
//取数据
String result = fileDB.get("name");
fileDB.put("name", "lisi");
String result2 = fileDB.get("name");
tv1.setText(result);
tv2.setText(result2);
二、在sharedPreferences中存储json格式数据存数据:
public static void saveApkEnalbleArray(Context context,boolean[] booleanArray) {
SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);
JSONArray jsonArray = new JSONArray();
for (boolean b : booleanArray) {
jsonArray.put(b);
}
SharedPreferences.Editor editor = prefs.edit();
editor.putString(APK_ENABLE_ARRAY,jsonArray.toString());
editor.commit();
}
取数据:
public static boolean[] getApkEnableArray(Context context,int arrayLength)
{
SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);
boolean[] resArray=new boolean[arrayLength];
Arrays.fill(resArray, true);
try {
JSONArray jsonArray = new JSONArray(prefs.getString(APK_ENABLE_ARRAY, "[]"));
for (int i = 0; i < jsonArray.length(); i++) {
resArray[i] = jsonArray.getBoolean(i);
}
} catch (Exception e) {
e.printStackTrace();
}
return resArray;
}
调用示例:
boolean[] booleanArray = {true,true,false,false};
saveApkEnalbleArray(this,booleanArray);
boolean[] resArray = getApkEnableArray(this,2);
tv1.setText(resArray[0]+"");