SharedPreference 在Android 開發過程中,被經常運用,今天來寫一下它的工具類
先介紹下 EdjApp ,屬於自定義的Android Application 創建全局變量
一、簡單的數據存儲方式,用來保存賬號、密碼等信息
二、用來保存多鍵值對象的id 等信息,如果我要獲取一組自定義的存儲對象,我可以先將它的id先保存下來
三、對象類型的數據存儲 一般用於自動登錄、浏覽歷史等
下面是工具類,serviceinfo對象是網絡獲取的信息對象,我會存儲並以查看時間的毫秒為對象的saveTime值
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.maq.api.ServiceInfo;
import com.maq.api.ServiceInfoComparator;
import com.maq.app.EdjApp;
public class SharedPreTools {
//單鍵值存儲----------------------------
public static String readShare(String sharename,String key) {
SharedPreferences user = EdjApp.getInstance().getSharedPreferences(sharename,0);
return user.getString(key, "");
}
public static void writeShare(String sharename,String key,String value ) {
SharedPreferences user = EdjApp.getInstance().getSharedPreferences(sharename, 0);
Editor editor = user.edit();
editor.putString(key, value);
editor.commit();
}
public static void removeShare(String sharename,String key ) {
SharedPreferences user = EdjApp.getInstance().getSharedPreferences(sharename, 0);
Editor editor = user.edit();
editor.remove(key);
editor.commit();
}
//多鍵值存儲
public static void writegroup(String sharename,String key,String value) {
SharedPreferences call = EdjApp.getInstance().getSharedPreferences(sharename, 0);
String group = call.getString(key, "");
if (group.indexOf(value) < 0) {
String newgroup = group + "," + key;
Editor editor = call.edit();
editor.putString(key, newgroup);
editor.commit();
}
}
public static void removegroup(String sharename,String key) {
SharedPreferences call = EdjApp.getInstance().getSharedPreferences(sharename, 0);
String group = call.getString(key, "");
String newgroup = group.replace("," + key, "");
Editor editor = call.edit();
editor.putString(key, newgroup);
editor.commit();
}
/**
* 儲存單條對象 serviceInfo
* @param per_name
* @param key
* @param vaule
*/
public static void saveServicePre(String per_name,String key,Object vaule){
SharedPreferences loginUserInfo = EdjApp.getInstance().
getSharedPreferences(per_name, Context.MODE_APPEND);
Editor preEd = null;
if(loginUserInfo != null){
preEd = loginUserInfo.edit();
}
if(preEd != null){
if(vaule != null){
ServiceInfo info1=(ServiceInfo)vaule;
info1.setSaveTime(getTimeId());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos=null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(info1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String info = new String(Base64.encodeBase64(baos.toByteArray()));
preEd.putString(key, info);
}
preEd.commit();
}
}
/**
* 讀取對象集合 serviceInfo
* @param per_name
* @param oblist
*/
public static <T> List<T> readAllServicePre(String per_name){
SharedPreferences loginUserInfo = EdjApp.getInstance().
getSharedPreferences(per_name, Context.MODE_APPEND);
Map<String, ?> maps = loginUserInfo.getAll();//取出所有數據
List<T> oblist = new ArrayList<T>();
Iterator it = maps.values().iterator();
while(it.hasNext()){
String base64Str = (String) it.next();
byte[] base64Bytes = Base64.decodeBase64(base64Str .getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois;
try {
ois = new ObjectInputStream(bais);
T tempobj = (T) ois.readObject();
oblist.add(tempobj);
// LoginUser loginUser = (LoginUser)tempobj;
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ArrayList<ServiceInfo>tempserviceInfo = new ArrayList<ServiceInfo>();
tempserviceInfo.addAll((Collection<? extends ServiceInfo>) oblist);
Comparator<ServiceInfo> ascComparator = new ServiceInfoComparator();
Collections.sort(tempserviceInfo, ascComparator);
oblist.clear();
oblist.addAll((Collection<? extends T>) tempserviceInfo);
return oblist;
}
/**
* 刪除單條對象數據
* @param per_name
* @param key
*/
public static void removeObjectPre(String per_name,String key){
SharedPreferences loginUserInfo = EdjApp.getInstance().
getSharedPreferences(per_name, Context.MODE_APPEND);
Editor preEd = null;
if(loginUserInfo != null){
preEd = loginUserInfo.edit();
}
preEd.remove(key);
preEd.commit();
}
//當前時間為id
public static long getTimeId() {
Date data = new Date();
long time=data.getTime();
return time;
}
//---------------------------
/**
* 儲存單條對象
* @param per_name
* @param key
* @param vaule
*/
public static void saveObjectPre(String per_name,String key,Object vaule){
SharedPreferences loginUserInfo = EdjApp.getInstance().
getSharedPreferences(per_name, Context.MODE_APPEND);
Editor preEd = null;
if(loginUserInfo != null){
preEd = loginUserInfo.edit();
}
if(preEd != null){
if(vaule != null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos=null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(vaule);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String info = new String(Base64.encodeBase64(baos.toByteArray()));
preEd.putString(key, info);
}
preEd.commit();
}
}
/**
* 讀取對象集合
* @param per_name
* @param oblist
*/
public static <T> List<T> readAllObjectPre(String per_name){
SharedPreferences loginUserInfo = EdjApp.getInstance().
getSharedPreferences(per_name, Context.MODE_APPEND);
Map<String, ?> maps = loginUserInfo.getAll();//取出所有數據
List<T> oblist = new ArrayList<T>();
Iterator it = maps.values().iterator();
while(it.hasNext()){
String base64Str = (String) it.next();
byte[] base64Bytes = Base64.decodeBase64(base64Str .getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois;
try {
ois = new ObjectInputStream(bais);
T tempobj = (T) ois.readObject();
oblist.add(tempobj);
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return oblist;
}
}
對象的排序,需要 根據設置的時間來算
import java.util.Comparator;
public class ServiceInfoComparator implements Comparator<ServiceInfo> {
@Override
public int compare(ServiceInfo object1, ServiceInfo object2) {
// TODO Auto-generated method stub
return Double.compare(object2.getSaveTime(), object1.getSaveTime());
}
}
這樣的存取就能獲得查看的歷史記錄,同時可以延伸到通話記錄,收藏等
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11