In activity in Toolbar I got a button which need to call method from fragment and update list in that fragment. Now it is an error. Calling in activity
@Over
I know this is an old post, but I just figured out what you could do. It is true that creating a fragment instance is not enough, It needs to be attached to Activity through a transaction. However, you can initially add both fragments and detach them from fragment manager. That way, they are both 'alive' in fragmentManager and you can call attach and detach on those fragments later as you wish.
i.e
.add(container, fragment1).detach(fragment1).add(container, fragment2).commit();
.
.
.
.
.
ft.detach(fragment2)
ft.attach(fragment1
Using commit()
can not solve the problem, we should try to find the solution in the source code of Fragment.
So, consider from the error stack you provided, the requireContext()
in Fragment was:
public final Context requireContext() {
Context context = getContext();
if (context == null) {
throw new IllegalStateException("Fragment " + this + " not attached to a context.");
}
return context;
}
This means the system will check the Context
from getContext()
, if it's null, the exception will be thrown.
So, to avoid this problem, we can check the result of getContext()
before do our business.
Create a fragment instance is not enough.
It needs to be attached to Activity through a transaction:
getFragmentManager()
.beginTransaction()
.replace(R.id.container_layout, fragment)
.commit();
After a successful commit, onAttach
method in the fragment is called, the view is created and then you can interact with its views.
In your case, create the fragment instance and attach it in activity onCreate
, then call sortByPopularity
later in a click event.
Read more about fragment life cycle: https://developer.android.com/guide/components/fragments
If you are using CountDownTimer, you may get that error cause of detaching the fragment before finishing the timer. If you are performing ui changes in onFinish callback, you should check the context that it is null or not like below;
timer = object : CountDownTimer(startTimeInMillis, 1000) {
override fun onTick(millisUntilFinished: Long) {
}
override fun onFinish() {
context?.let {
//perform ui changes here
}
}
}
timer?.start()
or you should cancel the timer before detaching fragment like below;
override fun onDestroy() {
super.onDestroy()
timer?.cancel()
}
Kotlin : Use Lazy Initialisation
override val contentMessage by lazy {
getString(R.string.message)
}
Kotlin:
My problem happened with getString()
Changing it to context.getString()
solved it