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 
    @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

但是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 {

    @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.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)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM