SnappyDb存储自定义对象时抛出异常 Maybe you tried to retrieve an array using this method ?

使用Snappy做本地数据缓存时,遇到如下异常:

E/ConfigUtil: com.snappydb.SnappydbException: Maybe you tried to retrieve an array using this method ? please use getObjectArray instead Class cannot be created (missing no-arg constructor): net.aimoqi.moqidump.bean.WeightBridge

两个类均作为ArrayList存储,分别是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class WeightBridgeCam{
private String ID;
// public WeightBridgeCam() {
// }
public WeightBridgeCam(String ID) {
this.ID = ID;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
@Override
public String toString() {
return "WeightBridgeCam{" +
"ID='" + ID + '\'' +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class WeightBridge{
private String id;
private String name;
private ArrayList<WeightBridgeCam> camList;
// public WeightBridge() {
// }
public WeightBridge(String id, String name, ArrayList<WeightBridgeCam> camList) {
this.id = id;
this.name = name;
this.camList = camList;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<WeightBridgeCam> getCamList() {
return camList;
}
public void setCamList(ArrayList<WeightBridgeCam> camList) {
this.camList = camList;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeightBridge that = (WeightBridge) o;
if (!id.equals(that.id)) return false;
return name.equals(that.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + name.hashCode();
return result;
}
}

百度了很久无果,也看了SnappyDB的Issues,并没有解决该问题。结果Google出一片文章
文中指出SnappyDB的一个好处就是存储的对象不用实现Serializable。但是必须保证存储的类遵循以下三个条件:

  1. 类必须有一个默认的(无参)的构造函数(The class must have a default (no-arg) constructor.)
  2. 类不能包含任何(非静态的)内部类(The class must not have any (non-static) inner classes.)
  3. 类中引用的任何类同样必须遵循上述两个规则(Any classes referenced in fields of your model class must also obey 1. and 2.)

对于我之前遇到的问题,针对第1点,为每个类添加一个默认的构造函数即可解决此问题。

1
2
3
4
5
6
7
public class WeightBridgeCam{
...
public WeightBridgeCam() {
}
...

1
2
3
4
5
6
7
public class WeightBridge{
...
public WeightBridge() {
}
...