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
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
这是因为Room中不支持对象中直接存储集合。
下面是要存储的对象Bean
@Entity public class ChatBean {private String msg;private int code;@NonNull@PrimaryKeyprivate String id = "";private List<ChatItem> data;@Entitypublic static class ChatItem {@PrimaryKeyprivate 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.bdcar.common.GsonInstance; import com.google.gson.reflect.TypeToken;import java.lang.reflect.Type; import java.util.List;public class ChatItemConverter {@TypeConverterpublic String objectToString(List<ChatBean.ChatItem> list) {return GsonInstance.getInstance().getGson().toJson(list);}@TypeConverterpublic 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.bdcar.common;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)
总结
以上是生活随笔为你收集整理的Android中在使用Room时提示:Cannot figure out how to save this field into database. You can consider adding a的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Android中ListView的使用以
- 下一篇: Android中使用Room时怎样存储带