学习Android代码的一些心得笔记 。
1.什么是序列化
序列化: 将数据结构或对象转换成二进制串的过程。
反序列化:将在序列化过程中所生成的二进制串转换成数据结构或者对象的过程。
2.什么情况下需要序列化
当你想把的内存中的对象保存到一个文件中或者数据库中时候;
当你想用套接字在网络上传送对象的时候;
3、如何实现序列化
将需要序列化的类实现Serializable接口就可以了。
public class Person implements Serializable{
private int age;
private String name;
//...seter()and geter()
}
栗子1:使用intent传递对象
1.传递对象
Person person = new Person();
person.setName("狗蛋");
person.serAge(22);
Intent intent = new Intent(FiratActivity.this,SecondActivity.this);
intent.putExtra("person_data",person);
startActivity(intent);
2.获取对象
//使用getSerializableExtra();
Person person = (Person)getIntent().getSerializableExtra("person_data");
栗子2:将对象缓存到本地
1.将网络数据保存到本地
/**
* 将网络数据保存到本地
*
* @param ser 要被缓存的对象
* @param file 文件名/路径
* @return
*/
public static boolean saveObject(Serializable ser, String file) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = mContext.openFileOutput(file, mContext.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ser);
oos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
oos.close();
} catch (Exception e) {
}
try {
fos.close();
} catch (Exception e) {
}
}
}
2.读取对象
/**
* 读取对象
*
* @param file
* @return Serializable 可向下转型为所需要的对象
* @throws IOException
*/
public static Serializable readObject(String file) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
// fis = AppContext.getInstance().openFileInput(file);
fis = mContext.openFileInput(file);
ois = new ObjectInputStream(fis);
return (Serializable) ois.readObject();
} catch (FileNotFoundException e) {
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (Exception e) {
}
try {
fis.close();
} catch (Exception e) {
}
}
return null;
}