admin管理员组

文章数量:1794759

Android中在使用Room时提示:Cannot figure out how to save this field into database. You can consider adding a

Android中在使用Room时提示:Cannot figure out how to save this field into database. You can consider adding a

场景

在Android中使用Room进行存储数据库时提示:

Cannot figure out how to save this field into database. You can consider adding a type converter for

 

注:

博客:blog.csdn/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。

实现

这是因为Room中不支持对象中直接存储集合。

下面是要存储的对象Bean

@Entity public class ChatBean {     private String msg;     private int code;     @NonNull     @PrimaryKey     private String id = "";     private List<ChatItem> data;     @Entity     public static class ChatItem {         @PrimaryKey         private int id;         private String msgNum;         private String content;         //语音消服务器地址         private String remoteContent;         private String sender;         private String receiver;         private String type;         private boolean canReceived;         private String sendTime;         private String receivedTime;         //语音时长         private int voiceDuration;         private boolean isRead;     } }

上面省略了get和set方法,在bean中还有个 对象集合data,对象为ChatItem

所以需要新建一个转换类ChatItemConverter

名字根据自己业务去定

package com.bdtd.bdcar.database; import androidx.room.TypeConverter; import com.bdtd.bdcar.bean.ChatBean; import com.bdtd.bdcarmon.GsonInstance; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; public class ChatItemConverter {     @TypeConverter     public String objectToString(List<ChatBean.ChatItem> list) {         return GsonInstance.getInstance().getGson().toJson(list);     }     @TypeConverter     public List<ChatBean.ChatItem> stringToObject(String json) {         Type listType = new TypeToken<List<ChatBean.ChatItem>>(){}.getType();         return GsonInstance.getInstance().getGson().fromJson(json, listType);     } }

此转换类的功能是实现对象与json数据的转换。

为了使用方便,这里将gson抽离出单例模式

所以新建GsonInstance

package com.bdtd.bdcarmon; import com.google.gson.Gson; public class GsonInstance {     private static GsonInstance INSTANCE;     private static Gson gson;     public static GsonInstance getInstance() {         if (INSTANCE == null) {             synchronized (GsonInstance.class) {                 if (INSTANCE == null) {                     INSTANCE = new GsonInstance();                 }             }         }         return INSTANCE;     }     public Gson getGson() {         if (gson == null) {             synchronized (GsonInstance.class) {                 if (gson == null) {                     gson = new Gson();                 }             }         }         return gson;     } }

然后转换类新建完成。

在上面的实体bean,ChatBean上面添加注解。

@TypeConverters(ChatItemConverter.class)

 

 

本文标签: 提示figureandroidRoomDatabase