我的MainActivity中有一个BottomNavigationView,有3个片段可以在它们之间进行切换。
这3个片段的内容几乎相同,但有一些小的命名更改,将显示带有FirebaseDatabase数据的recyclerView
FruitsFragment.kt:
class FruitsFragment :Fragment() {
private val adapter = GroupAdapter<GroupieViewHolder>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_fruits,container,false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val ref = FirebaseDatabase.getInstance().getReference("/Fruits/")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
if (isAdded && activity !=null ){
p0.children.forEach {
val data = it.getValue(UpdateRow::class.java) ?: return
val vegetableName = it.key
val price = data.p
val priceFormatted = PriceQuantityFormat.priceFormat(price)
val quantity = data.q
val downloadURL = data.downloadURL
adapter.add(VegetableRow(requireContext(),ftFragment,vegetableName!!,price,priceFormatted,quantity,downloadURL))
}
}
else {
Toast.makeText(requireContext(),"Error: too fast",Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(p0: DatabaseError) {
}
})
fruitsRV.adapter = adapter
}
}
这是我的片段,所有数据加载都进入我的适配器(使用Groupie),这只是简单地加载textViews
现在,在这些片段之间加载内容之前,快速切换会使我的应用崩溃。
我尝试按照该论坛上另一则帖子的建议检查iFyreed(),但根本没有起作用。 还尝试在任何地方都找不到答案的情况下进行搜索。
谢谢。
编辑:错误日志
Process: com.example.myapplication, PID: 5021
java.lang.IllegalStateException: Fragment VegetablesFragment{6f7374 (10863cd2-1ac1-4318-8959-cd11218fee65)} not attached to a context.
at androidx.fragment.app.Fragment.requireContext(Fragment.java:774)
at com.example.myapplication.VegetablesFragment$onActivityCreated$1.onDataChange(VegetablesFragment.kt:49)
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:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)