【发布时间】:2021-10-22 16:51:14
【问题描述】:
请有人帮助我!我在做一个小项目,我有这个功能:
private fun getRoutePoints(routeId: String) {
val dbReference = FirebaseDatabase.getInstance().getReference("/routes/$routeId")
val listOfPoints: MutableList<PointOfInterest> = mutableListOf()
dbReference.child("pointsOfInterest").get().addOnSuccessListener { pointsArray ->
pointsArray.children.forEach { point ->
val dataMap = point.value as Map<*, *>
val routeIdToInsert = routeId.toInt()
val id = point.key!!.toInt()
val pointOfInterest = PointOfInterest(
id = id,
title = dataMap["title"].toString(),
description = dataMap["description"].toString(),
latitude = dataMap["latitude"].toString().toDouble(),
longitude = dataMap["longitude"].toString().toDouble(),
imageUrl = dataMap["imageUrl"].toString(),
routeId = routeIdToInsert
)
listOfPoints.add(id, pointOfInterest)
if (pointsArray.children.count() == listOfPoints.size) {
CoroutineScope(Dispatchers.IO).launch {
AppDatabase.getInstance(application).routeDao.insertRoutePoints(listOfPoints)
}
}
}
}
}
当第二次插入完成时出现,执行再次返回到 for each,就像所有子级都没有被循环一样
我的 DAO 课程
> @Dao interface RouteDao {
> @Insert(onConflict = IGNORE)
> suspend fun insertRoute(route: Route)
>
> @Query("SELECT * FROM routes_tbl")
> fun getAllRoutes(): List<Route>
>
>
>
> @Transaction
> @Insert
> fun insertRoutePoints(points: List<PointOfInterest>) }
我的实体: 我的路线实体:
> @Entity(tableName = "routes_tbl") data class Route(
> @PrimaryKey(autoGenerate = false) val id: Int,
> @ColumnInfo(name = "title") val title: String,
> @ColumnInfo(name = "description") val description: String,
> @ColumnInfo(name = "historic_period") val historicPeriod: String,
> @ColumnInfo(name = "image_url") val imageUrl: String )
我的 PointOfInterest 实体:
> @Entity(tableName = "points_tbl", foreignKeys = [
> ForeignKey(
> entity = Route::class,
> parentColumns = ["id"],
> childColumns = ["route_id"],
> onDelete = CASCADE,
> onUpdate = CASCADE
> )]) data class PointOfInterest(
> @PrimaryKey(autoGenerate = false) val id: Int,
> @ColumnInfo(name = "title") val title: String,
> @ColumnInfo(name = "description") val description: String,
> @ColumnInfo(name = "latitude") val latitude: Double,
>
> @ColumnInfo(name = "longitude") val longitude: Double,
> @ColumnInfo(name = "image_url") val imageUrl: String,
> @ColumnInfo(name = "route_id") val routeId: Int )
关系为 1-N 的实体:
data class RouteWithPointsOfInterest(
@Embedded val route: Route,
@Relation(
parentColumn = "id",
entityColumn = "route_id"
) val pointsOfInterest: List<PointOfInterest>
)
您可以在此处克隆项目
【问题讨论】:
标签: android kotlin android-room