最近项目中需要存储对象数组,想利用SharePreferences进行存储,发现不行,不可以直接存储,后来查了资料,可以先专为了字节数组,存到本地,需要的时候读取转化就可以了。
SharedPreferences只能保存简单类型的数据,例 如,String、int等。如果想用SharedPreferences存取更复杂的数据类型(类、图像等),就需要对这些数据进行编码。我们通常会将 复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在 XML文件中。
注:Base 64是apathe的开源jar包,需要从http://commons.apache.org/proper/commons-codec/download_codec.cgi,下载,最好下载最新的。
package hhf.save; 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.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.codec.binary.Base64; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; /** * SharedPreferences中写入、读取对象操作 * @author huanghaifeng * */ public class SaveObjectActivity extends Activity { /** Called when the activity is first created. */ private SharedPreferences mySharedPreferences; private List<Map<String,Object>> wordList = new ArrayList<Map<String,Object>>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mySharedPreferences = getSharedPreferences("new_word", Activity.MODE_WORLD_READABLE); saveObjectToShared(); readObjectFromShared(); } /** * 将对象保存到SharedPreferences */ private void saveObjectToShared(){ Map<String,Object> map = new HashMap<String, Object>(); map.put("name", "张三"); map.put("age", "19"); wordList.add(map); map = new HashMap<String, Object>(); map.put("name", "李四"); map.put("age", "29"); wordList.add(map); ByteArrayOutputStream baos = new ByteArrayOutputStream(3000); ObjectOutputStream oos=null; try { oos = new ObjectOutputStream(baos); oos.writeObject(wordList); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 将Product对象放到OutputStream中 // 将Product对象转换成byte数组,并将其进行base64编码 String newWord = new String(Base64.encodeBase64(baos.toByteArray())); SharedPreferences.Editor editor = mySharedPreferences.edit(); // 将编码后的字符串写到base64.xml文件中 editor.putString("newWord", newWord); editor.commit(); } /** * 从SharedPreferences中读取对象 */ private void readObjectFromShared(){ String wordBase64 = mySharedPreferences.getString("newWord", ""); // 对Base64格式的字符串进行解码 byte[] base64Bytes = Base64.decodeBase64(wordBase64 .getBytes()); ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes); ObjectInputStream ois; try { ois = new ObjectInputStream(bais); List<Map<String,Object>> result = (List<Map<String, Object>>) ois.readObject(); for (Map<String,Object> map: result) {
//得到你想要的数据进行处理 } System.out.println("result = " + result); } 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(); } } }