Google JetPack Room不支持 泛型的TypeConverter 吗?

使用room后感觉上手还挺好的,就是遇到了个转换器的问题

其实我就想保存外层List数据在数据库,里面List数据也是很重要的,想保存在一个表,里层只能先保存jsonString形式了,然后就遇到转换器的问题。

数据模型:

public class MyBean {
    private List<DataBean> data;

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }
    
    @Entity(tableName = "data_table")
    @TypeConverters({ AConverts.class, BConverts.class })
    public static class DataBean implements Serializable {

        @PrimaryKey
        private long id;
        private long account_id;

        @ColumnInfo(name = "a_column")
        private List<A> aList;
        @ColumnInfo(name = "b_column")
        private List<B> bList;

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public long getAccountId() {
            return id;
        }

        public void setAccountId(long account_id) {
            this.account_id = account_id;
        }

        public List<A> getA() {
            return aList;
        }

        public void setA(List<A> aList) {
            this.aList = aList;
        }

        public List<B> getB() {
            return bList;
        }

        public void setB(List<B> bList) {
            this.bList = bList;
        }

        public static class A {

            private int start_time;

            public int getStart_time() {
                return start_time;
            }

            public void setStart_time(int start_time) {
                this.start_time = start_time;
            }
        }

        public static class B {
            private int weekday;

            public int getWeekday() {
                return weekday;
            }

            public void setWeekday(int weekday) {
                this.weekday = weekday;
            }
        }
    }
}

转换器

public class AConverts {
    @TypeConverter
    public List<DataBean.A> stringToObject(String value) throws IXJsonErrorException {
        Gson gson = new Gson();
        if (value == null) {
            return Collections.emptyList();
        }
        Type listType = new TypeToken<List<DataBean.A>>() {}.getType();
        return gson.fromJson(value, listType);
    }

    @TypeConverter
    public String objectToString(List<DataBean.A> aList) {
        Gson gson = new Gson();
        return gson.toJson(aList);
    }
}


public class BConverts {
    @TypeConverter
    public List<DataBean.B> stringToObject(String value) throws IXJsonErrorException {

        Gson gson = new Gson();
        if (value == null) {
            return Collections.emptyList();
        }
        Type listType = new TypeToken<List<DataBean.B>>() {}.getType();
        return gson.fromJson(value, listType);
    }

    @TypeConverter
    public String objectToString(List<DataBean.B> bList) {
        Gson gson = new Gson();
        return gson.toJson(bList);
    }
}

如果使用泛型添加一个通用的转换器则会报错

这个才两个转换器

我的项目中其实有四个,这个岂不是要写死我。。。。。

如果新添加需要转换器的类岂不是又要写。。。。

有没有遇到同样痛苦的同学,欢迎留言探讨

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,以下是实现安卓开发 compose 现在有一个List<Note> 要实现拖动排序功能jetpack room数据库的 kotlin 代码示例: 首先,您需要在 build.gradle 文件中添加以下依赖: ``` implementation "androidx.compose.foundation:foundation-layout:1.0.0-beta02" implementation "androidx.compose.material:material:1.0.0-beta02" implementation "androidx.compose.runtime:runtime-livedata:1.0.0-beta02" implementation "androidx.compose.ui:ui:1.0.0-beta02" implementation "androidx.compose.ui:ui-tooling:1.0.0-beta02" implementation "androidx.room:room-runtime:2.3.0" kapt "androidx.room:room-compiler:2.3.0" ``` 然后,您可以使用 Jetpack Compose 实现一个可拖动的列表,并使用 Room 数据库存储和加载数据。以下是完整的 Kotlin 代码: ``` import androidx.compose.foundation.background import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @Entity(tableName = "notes") data class Note( @PrimaryKey val id: Int, @ColumnInfo(name = "text") val text: String, @ColumnInfo(name = "position") var position: Int ) @Dao interface NoteDao { @Query("SELECT * FROM notes ORDER BY position ASC") fun getNotes(): LiveData<List<Note>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(note: Note) @Update suspend fun update(note: Note) } @Database(entities = arrayOf(Note::class), version = 2) abstract class AppDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao companion object { private var instance: AppDatabase? = null fun getInstance(context: Context): AppDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } private fun buildDatabase(context: Context): AppDatabase { return Room.databaseBuilder(context, AppDatabase::class.java, "notes.db") .addMigrations(object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE notes ADD COLUMN position INTEGER DEFAULT 0") } }) .build() } } } class NoteViewModel : ViewModel() { private val appDatabase = AppDatabase.getInstance(MyApplication.context) private val noteDao = appDatabase.noteDao() private val _notes = MutableLiveData<List<Note>>() init { loadNotes() } fun getNotes(): LiveData<List<Note>> { return _notes } fun addNote() { viewModelScope.launch(Dispatchers.IO) { val count = noteDao.getNotes().value?.size ?: 0 noteDao.insert(Note(count + 1, "Note ${count + 1}", count + 1)) } } fun updateNotePosition(note: Note, position: Int) { viewModelScope.launch(Dispatchers.IO) { note.position = position noteDao.update(note) } } private fun loadNotes() { viewModelScope.launch(Dispatchers.IO) { val notes = noteDao.getNotes().value ?: emptyList() _notes.postValue(notes) } } } @Composable fun NotesList(noteViewModel: NoteViewModel) { val notes by noteViewModel.getNotes().observeAsState(listOf()) Column(modifier = Modifier.padding(16.dp)) { Button(onClick = { noteViewModel.addNote() }) { Text("Add Note") } for (i in notes.indices) { val note = notes[i] Box( modifier = Modifier .fillMaxSize() .alpha(if (note.position == i) 1f else 0.5f) .background(Color.White) .draggable( orientation = Orientation.Vertical, onDragStarted = { /* Do nothing */ }, onDragStopped = { noteViewModel.updateNotePosition(note, it) } ) ) { Text( text = note.text, modifier = Modifier.padding(16.dp) ) } } } } class MainActivity : ComponentActivity() { private val noteViewModel by viewModels<NoteViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NotesList(noteViewModel) } } } ``` 代码说明: 1.定义 Note 实体类,其中包含 id、text 和 position 字段。 2.定义 NoteDao 接口,其中包含 getNotes()、insert() 和 update() 函数。 3.AppDatabase 是一个 Room 数据库,它包含 NoteDao。 4.NoteViewModel 是一个 ViewModel,它包含一个 LiveData 列表,用于存储 Note 对象列表。 5.NotesList 是一个 Composable 函数,它显示 Note 对象列表,并允许用户重新排序它们。 6.在主 Activity 中使用 NotesList Composable 函数。 该代码依赖于 Jetpack Compose 和 Room 数据库。Jetpack Compose 提供了一种简单的方法来实现可拖动的列表,而 Room 数据库用于保存和加载 Note 数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值