Android中使用Room时怎样存储带list集合的对象
生活随笔
收集整理的這篇文章主要介紹了
Android中使用Room时怎样存储带list集合的对象
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
Android中使用Room(ORM關系映射框架)對sqllite數據庫進行增刪改查:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/110821348
上面講了使用Room對簡單的對象進行存取到數據庫。
但是如果對象中含有list集合屬性,形如下面這種
@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
但是Room中不支持對象中直接存儲集合。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
所以需要新建一個轉換類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时怎样存储带list集合的对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中在使用Room时提示:C
- 下一篇: SpringBoot中通过重写WebMv