Я пытаюсь заставить LiveData Observer работать, и все работает, но через неделю мое приложение продолжает падать, когда фрагмент прикрепляется к моей активности с живыми данными.Фрагмент очень прост, он имеет RecyclerView, который отображает список Bloggers
в сетке.ViewModel выглядит следующим образом:
class SimpleBloggersViewModel : ViewModel() {
var bloggers: MutableLiveData<List<Blogger>> = MutableLiveData()
}
И я инициализирую его в своем фрагменте, используя:
private val viewModel: SimpleBloggersViewModel by lazy {
ViewModelProvider(this).get(SimpleBloggersViewModel::class.java)
}
Код, который вызывает сбой, следующий:
override fun onAttach(context: Context) {
super.onAttach(context)
try {
viewModel.bloggers.observe(viewLifecycleOwner, Observer { changeObserver })
} catch (e: IllegalStateException) {
Log.e(TAG, "onAttach: Failed to attach BloggersFragment.", e)
}
}
Без try / catch в методе onAttach
я получаю следующее загадочное исключение (и сбой приложения)
Process: com.mydomain.appname, PID: 31393
java.lang.IllegalStateException: Already attached
at androidx.fragment.app.FragmentManager.attachController(FragmentManager.java:3000)
at androidx.fragment.app.Fragment.performAttach(Fragment.java:2622)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1291)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1264)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1147)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:120)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2369)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2327)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2230)
at androidx.fragment.app.FragmentManager$3.run(FragmentManager.java:414)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
После добавления блока try / catch, который вы видите выше, исключение становитсянемного больше информации, но я все еще не могу понять, что вызывает проблему.
java.lang.IllegalStateException: You can consumeRestoredStateForKey only after super.onCreate of corresponding component
at androidx.savedstate.SavedStateRegistry.consumeRestoredStateForKey(SavedStateRegistry.java:77)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:65)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:177)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:145)
at com.mydomain.appname.Bloggers.BloggersFragment$viewModel$2.invoke(BloggersFragment.kt:31)
at com.mydomain.appname.Bloggers.BloggersFragment$viewModel$2.invoke(BloggersFragment.kt:28)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at com.mydomain.appname.Bloggers.BloggersFragment.getViewModel(Unknown Source:7)
at com.mydomain.appname.Bloggers.BloggersFragment.onAttach(BloggersFragment.kt:90)
at androidx.fragment.app.Fragment.performAttach(Fragment.java:2638)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1291)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1264)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1147)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:120)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2369)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2327)
at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:2199)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:303)
at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:236)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:743)
at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:815)
at android.view.View.measure(View.java:22238)
at androidx.drawerlayout.widget.DrawerLayout.onMeasure(DrawerLayout.java:1119)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
2019-09-19 12:18:11.181 31963-31963/com.mydomain.appname E/BloggersFragment: at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22238)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6682)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:725)
at android.view.View.measure(View.java:22238)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2531)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1558)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1826)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1446)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7014)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:916)
at android.view.Choreographer.doCallbacks(Choreographer.java:728)
at android.view.Choreographer.doFrame(Choreographer.java:660)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:902)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
Обратите внимание, что я вызываю super для всех переопределяющих методов, прежде чем делать что-то еще, так что второе исключение все ещене помогает мне понять ошибкуЛюбая помощь очень ценится.Спасибо за ваше время.