1

I have a simple fragment as shown below.

class GradesFragment : Fragment(R.layout.fragment_grades) {

   ...

    companion object {

        @JvmStatic
        fun newInstance() = GradesFragment()
    }
}

I added this fragment to MainActivity as the following.

class MainActivity : AppCompatActivity(R.layout.activity_main) {

    supportFragmentManager.beginTransaction()
        .replace(R.id.frameLayout, GradesFragment.newInstance())
        .addToBackStack("tagMainFragment")
        .commit()

}

When I tested my app in prod and debug, there is no crash. However, my app crashes in prod users, firebase crashlytics shows many errors. No specific device or no specific version. Many android versions and devices faces this crash.

It shows the following error: androidx.fragment.app.Fragment$d: Unable to instantiate fragment com.xxx.yyy.d.b: could not find Fragment constructor

To be able to use fragment and activity constructor, should I add somethings to proguard file? What am I missing? Why some users faces crash but some other user do not face crash ?

metis
  • 1,024
  • 2
  • 10
  • 26
  • Hi @metis, using Fragment constructor with parameters is considered to be bad practise. I think you can find an answer in this [thread](https://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment). – DmitryArc Oct 14 '20 at 14:54
  • https://android.jlelse.eu/define-resource-layout-id-in-the-constructor-activity-fragment-with-androidx-a9f80674f185. look at the link please. – metis Oct 14 '20 at 14:59
  • Hello! I think you should remove @JvmStatic and follow this steps -> https://stackoverflow.com/questions/52268841/how-to-fix-this-bug-using-kotlin-could-not-find-fragment-constructor – rguzman Oct 14 '20 at 15:12

2 Answers2

0

I found that the crash occurs when the device orientation changes. I forced my activity to be portrait orientation, this solved the crash issue. I couldn't find a better solution.

metis
  • 1,024
  • 2
  • 10
  • 26
0

Actually, it's crashing because an orientation change will rebuild the fragment. Rebuilding the fragment might also happen if RAM is low, and the user receives a call, forcing Android to destroy your fragment and rebuild it later.

Change this line:

class GradesFragment : Fragment(R.layout.fragment_grades)

to this:

class GradesFragment : Fragment()

R.layout.fragment_grades should be accessed somewhere else. A common way to use it would be something like

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_grades, container, false)
}
Muz
  • 5,866
  • 3
  • 47
  • 65