Reputation: 76
I was trying to refresh the fragment when pressing back from an activity, I tried using onResume() and onStop() and it worked but... another issue comes. using onResume() and onStop() inside the fragment is making the fragment refresh too many times that the app is crashing and I really don't know what I am doing wrong, if you can please help me with this issue
my onResume() function
override fun onResume() {
super.onResume()
//shoudRefreshOnResume is a global var
if (shouldRefreshOnResume) {
val ft: FragmentTransaction = parentFragmentManager.beginTransaction()
ft.detach(this).attach(this).commit()
}
}
my onStop() function
override fun onStop() {
super.onStop()
shouldRefreshOnResume = true
}
my onCreateView() function
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_home, container, false)
val foodButton = root.findViewById<Button>(R.id.mainFoodButton)
val recentlyViewed = root.findViewById<LinearLayout>(R.id.recently_viewedView)
foodButton.setOnClickListener {
val intent = Intent(activity, CategoriesActivity::class.java)
startActivity(intent)
}
//createRecentlyViewedButton() is a function
createRecentlyViewedButton(recentlyViewed)
return root
}
Upvotes: 1
Views: 3777
Reputation: 76
I fixed the issue by replacing onStop() function to onPause() since the activity is not getting destroyed and it no longer loop the createRecentlyViewedButton() function hope this help somebody
here are the changes I made though
override fun onPause() {
super.onPause()
shouldRefreshOnResume = true
}
and
override fun onResume() {
super.onResume()
//shoudRefreshOnResume is a global var
if (shouldRefreshOnResume) {
val recentlyViewed = activity?.findViewById<LinearLayout>(R.id.recently_viewedView)
createRecentlyViewedButton(recentlyViewed!!)
}
}
Upvotes: 1