0

Users will face problems like Could not find Fragment constructor when rotates phone or changes to a Dark mode(when My activity recreates).

Unable to start activity ComponentInfo{e.Quran.Qaz/e.Quran.Qaz.ui.Zhuz.QuranByPage}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment e.Quran.Qaz.ui.Zhuz.PageFragment: could not find Fragment constructor

I have multiple places in my project, where I have to use Fragments. I have solved almost everything with this solution. However, I have to initialize my Fragment with the listener. But, with this solution it is impossible. I wasn't able to comment on that answer due to my StackOverflow reputation.

There was an accepted answer. There was said:

All Fragment classes you create must have a public, no-arg constructor. In general, the best practice is to simply never define any constructors at all and rely on Java to generate the default constructor for you.

And suggested initializing Fragment like this:

public static ProductsFragment newInstance(String id) {
    Bundle args = new Bundle();
    args.putString("id", id);
    ProductsFragment f = new ProductsFragment();
    f.setArguments(args);
    return f;
}

Are there any ways to initialize it with Listener in the newInstance method? P.S. I would appreciate any help. It is one of my first questions, don't judge me so strong. :)

prsnlme
  • 179
  • 8

1 Answers1

0

Solution is here

Non-default constructors in fragments with DatePicker Callback

In the answer, that worked for me there was written:

  1. The fragment should have an Empty constructor If you don't want to have issues with configurations changed such as screen rotation or low memory case. When configurations changed, Android will re-create Fragment using an empty constructor automatically.
  2. For your case. DateChangeListener should be implemented by Host Activity - If you Open DatePickerFragment from Activity TargetFragment (by setting setTargetFragment from Fragment) - If you open DatePickerFragment from Fragment (like parent fragment)
  3. From DatePickerFragment, you can access DateChangeListener by casting as below: (DateChangeListener)this.getActivity() ----> If the host activity implement DateChangeListener (DateChangeListener)this.getTargetFragment() ---> If the parent fragment (setTargetFragment) implement DateChangeListener

It was duplicated question, with another context. So I won't delete this question.

prsnlme
  • 179
  • 8