房间数据库中的一对多关系



我的项目中有一个事件,该事件有时间表。每个事件都有自己的时间表。我想用我写的代码列出每个事件的时间表,但我无法通过适配器访问它。

我的实体;

事件:

@Parcelize
@Entity(tableName = "event_table")
data class Event(
@PrimaryKey(autoGenerate = true)
val eventId: Int,
val eventName: String,
val eventCategory: String
): Parcelable

时间线:

@Parcelize
@Entity(tableName = "timeline_table")
data class Timeline(
@PrimaryKey(autoGenerate = true)
val TimeLineId: Int,
val TimeLineAccomplish: String,
val TimeLineDetails: String,
val TimeLineDate: String,
val eventCreatorId: Int
): Parcelable

事件和时间线:

data class EventAndTimeline(
@Embedded val event: Event,
@Relation(
parentColumn = "eventId",
entityColumn = "eventCreatorId"
)
val timeline: List<Timeline>
)

数据库:

@Database(entities = [Timeline::class, Event::class], version = 1, exportSchema = false)
abstract class TimeLineDatabase: RoomDatabase() {
abstract fun timelineDao(): TimelineDao
abstract fun eventDao(): EventDao
companion object{
@Volatile
private var INSTANCE: TimeLineDatabase? = null
fun getDatabase(context: Context): TimeLineDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
TimeLineDatabase::class.java,
"timeline_database"
)
.build()
INSTANCE = instance
return instance
}
}
}
}

刀:

@Dao
interface TimelineDao{
@Transaction
@Query("SELECT * FROM event_table")
fun getEventsWithTimelines(): LiveData<List<EventAndTimeline>>
}

存储库:

class TimelineRepository(private val timelineDao: TimelineDao) {

val readAllData: LiveData<List<EventAndTimeline>> = timelineDao.getEventsWithTimelines()
}

ViewModel:

class TimeLineViewModel(application: Application): AndroidViewModel(application) {
val readAllData: LiveData<List<EventAndTimeline>>

private val timelineRepository: TimelineRepository
init {
val timelineDao = TimeLineDatabase.getDatabase(application).timelineDao()
timelineRepository = TimelineRepository(timelineDao)
readAllData = timelineRepository.readAllData
}

最后:在我的列表适配器中,我想列出事件的时间表。当我没有关系时,我用到达所有时间线

holder.itemView.findViewById<TextView>(R.id.timelineDetails_txt).text 
currentItem.TimeLineDetails 

但现在我看不到时间线变量(如TimeLineDetails、TimeLineComplete等(

您需要像下面的例子一样编写一个查询。

interface UserBookDao {
@Query(
"SELECT user.name AS userName, book.name AS bookName " +
"FROM user, book " +
"WHERE user.id = book.user_id"
)
fun loadUserAndBookNames(): LiveData<List<UserBook>>

// You can also define this class in a separate file.
data class UserBook(val userName: String?, val bookName: String?)
}

您可以在下面的链接中查看更多示例。

https://developer.android.com/training/data-storage/room/relationships

相关内容

  • 没有找到相关文章

最新更新