我正在尝试在android中实现按名称搜索地点。我创建了两个实体,Word
和Place
。
@Parcelize
@Entity
data class Place(
@PrimaryKey
val id: String,
val name: String,
val icon: String,
val latitude: Double,
val longitude: Double,
val address: String
) : Parcelable
@Entity
data class Word(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val searchWord: String,
val placeId: String
)
我还创建了另一个data class
来模拟Word
和Place
之间的一对多关系。
data class WordWithPlaces(
@Embedded
val word: Word,
@Relation(parentColumn = "placeId", entityColumn = "id")
val places: List<Place>
)
我遇到的问题是,当我查询数据时,我得到了null
。
这是dao
中的查询功能。
@Transaction
@Query("SELECT * FROM Word WHERE searchWord = :searchWord")
fun getWordsWithPlaces(searchWord: String): LiveData<WordWithPlaces>
我需要帮助来使实施工作正常进行。
答案 0 :(得分:0)
我的错误是在体系结构中。
这不是一对多的关系,而是多对多的关系。我必须使用两个查询来实现搜索。
// search for places online based on a searchWord
// create words consisting of each place's id and the searchWord
// save the words and places in the database
suspend fun searchPlaces(searchWord: String) {
return try {
val searchResults: PlaceTextSearch = getNetworkService().searchPlaces(searchWord)
val places = searchResults.places
val words = places.map { Word(word = searchWord, placeId = it.id) }
dao.insertWords(words)
dao.insertPlaces(places)
} catch (e: Exception) {
e.printStackTrace()
}
}
// get the words matching a searchword
// get all related places based on those words
suspend fun getPlaces(searchWord: String): List<Place> {
val words = dao.getWords(searchWord)
val placeIds = words.map { it.placeId }.toTypedArray()
return dao.getPlaces(placeIds)
}