日期:2014-05-20  浏览次数:20750 次

类序列化保存时有Bitmap成员出错
大家好!

我在保存类到文件的时候遇到了问题,其中一个类的成员Bitmap不支持序列化,导致读取的时候出错。

下面是一个简化的例子:
Java code
public class SerializableActivity extends Activity {
    testClass m_tc;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String l_path = Environment.getExternalStorageDirectory() + "/"+ "tssstt";
        Log.i("path",l_path);
        File l_f = new File(l_path);
        if (l_f.exists()) {  // 我把异常处理去掉了。。。
        ObjectInputStream l_i = new ObjectInputStream( new FileInputStream(l_path));                m_tc = (testClass) l_i.readObject();
        }
        else {
        ObjectOutputStream l_o = new ObjectOutputStream( new FileOutputStream(l_path));
        l_o.writeObject(m_tc);
        }
        TextView l_tv= (TextView)findViewById(R.id.aa);
        l_tv.setText(m_tc.name);
    }
}


Java code
public class testClass implements Serializable {
/*    public Bitmap m_Bitmap = null;      // 当为 null 的时候还是可以序列化的。
    public MyBitmap m_MyBitmap = new MyBitmap(BytesBitmap.getBytes(Bitmap.createBitmap(100, 
            100, Config.ARGB_8888)),"test"); */  // 这是把位图转换后使用,可以序列化。
               // 但是实际程序中需在多处频繁修改位图,这样做需要经常把字节转成位图,花费比较多。
    Bitmap m_Bitmap = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
    public transient String name = "dlkfjasdklf";
    
    // 下面两个方法是我加上测试的,以为不写Bitmap就没事,结果还是出错。空指针错。(去掉下面也一样错)
    private void writeObject(ObjectOutputStream stream) throws IOException {
        stream.defaultWriteObject();
        stream.writeObject(name);
    }
    
    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
        name = (String) stream.readObject();
    }
}


------解决方案--------------------
要么声明 transient ,序列化时忽略,要么自己继承Bitmap写序列化接口实现。
------解决方案--------------------
如果实现序列化接口的话,只会在进行序列化的时候发生调用,所以不用担心“这会引起不停地转换。。。”

不过你3楼的方案也不差,所以没啥大问题。