【问题标题】:Save object to sqlite db将对象保存到 sqlite db
【发布时间】:2017-02-13 19:17:54
【问题描述】:

我想将一个类对象保存到 db。我使用了 Serializable 但我的类中的一个对象始终为空。

 import com.google.android.gms.maps.model.LatLng;
 import java.io.Serializable;
 import java.util.ArrayList;
 public class A implements Serializable {
 protected String Name;
 protected int Type;
 protected transient List<LatLng> Nodes=new ArrayList<LatLng>();

}

nodes 始终为空。如果我删除“瞬态”,那么所有对象都变为空。

保存到db是这样的:

    public long InsertList(A Data) {

    byte[] bytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(Data);
        oos.flush();
        oos.close();
        bos.close();
        bytes = bos.toByteArray();
    } catch (IOException ex) {
        //TODO: Handle the exception
        ex.printStackTrace();
        ;
    }

    ContentValues insertValues = new ContentValues();
    insertValues.put("Data", bytes);
    insertValues.put("Selected", 1);
    return mDb.insert("Table", null, insertValues);

}

【问题讨论】:

标签: android database serializable


【解决方案1】:

Java中的transient关键字用来表示一个字段不应该被序列化。

所以在你的情况下节点不会被序列化。

看看这个Why does Java have transient fields?

【讨论】:

  • 为什么节点为空?
  • @FarzadShahbazi 因为暂态字段未序列化。因此它不能被解组。
  • @Code-Apprentice 如果我删除瞬态字段,为什么没有保存到数据库?
  • @FarzadShahbazi 您是否在序列化对象时检查了异常? Check details for Exceptions
  • @a.r.我没有例外。
猜你喜欢
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多