пожалуйста, помогите мне с моей проблемой.Я хотел бы получить LiveData из моей базы данных и отобразить его с повторным просмотром.У меня есть метод в репозитории, чтобы получить его из базы данных:
fun getEthTransactions(): LiveData<List<EthTransaction>> {
return mEthTransactionsDao.getTransactions()
}
И я проверил, что этот метод возвращает не нуль.
В ViewModel я делаю это:
private val ethRepository: EthRepository = EthRepository(application)
val transactionData: LiveData<List<EthTransaction>>
get() = ethRepository.getEthTransactions()
Во фрагменте я пытаюсь получить viewModel и связать с привязкой:
private val journalFragmentViewModel by lazy {
ViewModelProviders.of(this).get(JournalFragmentViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val activityJournalBinding : FragmentJournalBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_journal, container,false)
journalFragmentViewModel.transactionData.observe(this, Observer {
activityJournalBinding.viewModel = journalFragmentViewModel
JournalAdapter().journal = it
})
activityJournalBinding.viewModel = journalFragmentViewModel
activityJournalBinding.lifecycleOwner = this
return activityJournalBinding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val layoutManager = LinearLayoutManager(context)
recyclerView.layoutManager = layoutManager
recyclerView.hasFixedSize()
recyclerView.adapter = JournalAdapter()
recyclerView.addItemDecoration(DividerItemDecoration(context, layoutManager.orientation))
}
Адаптер моего recycleview:
class JournalAdapter : RecyclerView.Adapter<JournalAdapter.ViewHolder>() {
var journal: List<EthTransaction> = emptyList()
set(value){
field = value
notifyDataSetChanged()
}
override fun getItemCount() = journal.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(journal[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.view_journal,
parent,
false))
}
companion object {
@JvmStatic
@BindingAdapter("journal")
fun RecyclerView.bindItems(journal: List<EthTransaction>) {
val adapter = adapter as JournalAdapter
adapter.journal = journal
}
}
class ViewHolder (private val binding: ViewJournalBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind (item: EthTransaction) {
with(binding) {
viewJournalAccount.text = item.account
viewJournalAmount.text = item.amount
}
}
}
}
В ресурсах фрагмента я пытаюсь добавить информацию из viewModel:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:journal="@{viewModel.transactionData}"
/>
</LinearLayout>
Но когда я запускаю свое приложение в этом фрагменте, я получаю исключение в FragmentJournalBindingImpl, сгенерированном привязкой данных:
java.lang.RuntimeException: Failed to call observer method
at androidx.lifecycle.ClassesInfoCache$MethodReference.invokeCallback(ClassesInfoCache.java:226)
at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeMethodsForEvent(ClassesInfoCache.java:194)
at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeCallbacks(ClassesInfoCache.java:185)
at androidx.lifecycle.ReflectiveGenericLifecycleObserver.onStateChanged(ReflectiveGenericLifecycleObserver.java:36)
at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:361)
at androidx.lifecycle.LifecycleRegistry.forwardPass(LifecycleRegistry.java:300)
at androidx.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.java:339)
at androidx.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.java:145)
at androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.java:131)
at androidx.fragment.app.Fragment.performStart(Fragment.java:2590)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:918)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1235)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1301)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:710)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2071)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1861)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1816)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1723)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManagerImpl.java:146)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5444)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:727)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617)
Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter journal
at hellynx.poscryptos.ui.fragments.journal_fragment.JournalAdapter$Companion.bindItems(JournalAdapter.kt)
at hellynx.poscryptos.ui.fragments.journal_fragment.JournalAdapter.bindItems(JournalAdapter.kt)
at hellynx.poscryptos.databinding.FragmentJournalBindingImpl.executeBindings(FragmentJournalBindingImpl.java:129)
at androidx.databinding.ViewDataBinding.executeBindingsInternal(ViewDataBinding.java:463)
at androidx.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:435)
at androidx.databinding.ViewDataBinding$OnStartListener.onStart(ViewDataBinding.java:1674)
at java.lang.reflect.Method.invoke(Native Method)
Я полагаю, что неправильно обращаюсь к виватам, но из всехпримеры, которые я изучал, я до сих пор не понимаю, как это сделать правильно, помогите пожалуйста.