Попытка инициализировать дочерние данные Firebase в MutableList
Скриншот базы данных
Код
class RecipesItemRepository {
private val reference = FirebaseDatabase.getInstance().reference.child("recipes").child("test")
var recipesItem = MutableLiveData<List<RecipesItem>>()
fun onViewInitializedProducts() {
val postListener = object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val recipesData = ArrayList<RecipesItem>()
dataSnapshot.children.forEach {
recipesData.add(it.getValue(RecipesItem::class.java)!!)
}
recipesItem.value = recipesData
}
override fun onCancelled(databaseError: DatabaseError) {
Log.w("tag", "loadPost:onCancelled", databaseError.toException())
}
}
reference.addListenerForSingleValueEvent(postListener)
}
fun getChildrenByParent(parent: String): List<RecipesItem> {
onViewInitializedProducts()
var recipes = recipesItem.value
val children = mutableListOf<RecipesItem>()
recipes?.forEach {
if (it.parent == parent) {
children.add(it)
}
}
return children
}
}
Ошибка
Вот журнал запуска приложения. У меня есть эта ошибка при попытке намеренного фрагмента RecyclerView
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cookhelper, PID: 14895
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.cookhelper.navigation.recipes.RecipesItem
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@16.0.4:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@16.0.4:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@16.0.4:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@16.0.4:212)
at com.example.cookhelper.navigation.recipes.RecipesItemRepository$onViewInitializedProducts$postListener$1.onDataChange(RecipesItemRepository.kt:39)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@16.0.4:183)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Magi c
Получение данных из Firebase не работает, поэтому я попытался добавить локальные данные в список, и он работал правильно:
class RecipesItemRepository {
val recipesData = mutableListOf<RecipesItem>(
RecipesItem(
1,
"Burger",
"Food",
"https://www.insurancejournal.com/app/uploads/2019/11/impossible-burger-2-768x579.jpg",
"Dinner"
),
RecipesItem(
2,
"Fried Chicken",
"Food",
"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/fried-chicken-ghk-0619-1558621360.jpg?crop=0.808xw:0.808xh;0.0663xw,0.0976xh&resize=980:*",
"Evening dinner"
)
)
fun getChildrenByParent(parent: String): List<RecipesItem> {
val children = mutableListOf<RecipesItem>()
val recipes = recipesData
recipes?.forEach {
if (it.parent == parent) {
children.add(it)
}
}
return children
}
}
Это может быть ошибка при получении данных из базы данных, потому что отображаются локальные данные! Если это важно, данные инициализируются в виде переработчика.
Спасибо!