Unable to instantiate fragment make sure class name exists, is public, and has an empty constructor that is public
Is it because my Fr
As CommonsWare said make it static or standalone, additionally don't know why you need a shedload of refactoring for getting findViewById
to work. Suggestions:
Using the view inflated in onCreateView
,
inflatedView.findViewById(.....)
or calling it in onActivityCreated(.....)
getActivity().findViewById(......)
But even if you still need a load of refactoring then that might just be the way it is, converting an app to use fragments doesn't come for free having just finished a project doing so.
public static class MyDialogFragment extends DialogFragment {
public MyDialogFragment(){
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
LinearLayout main = new LinearLayout(getActivity());
main.setOrientation(LinearLayout.VERTICAL);
return (new AlertDialog.Builder(getActivity()).setTitle(
getText("Title")).setView(main).create());
}
}
In my case, I was missing the constructor, the post from @eoghanm above helped me
public static class MyDialogFragment extends DialogFragment {
public MyDialogFragment(){
}
...
}
Make sure the Fragment isn't abstract. Copy&paste makes this kind of things happen :(
Using setRetainInstance(true) worked for us. Our inner classes now look like this:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
Fragment fragment = new MySectionFragment();
Bundle args = new Bundle();
args.putInt(MySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
fragment.setRetainInstance(true);
return fragment;
}
// ...
}
public class MySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
@SuppressLint("ValidFragment")
public MySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
}
// ...
}
PS. Here's an interesting one about setRetainInstance(boolean): Understanding Fragment's setRetainInstance(boolean)
Hahah my hilarious issue was I had a call to getString()
as a member level variable in my fragment which is a big no no because it's too early I guess. I wish the error was more descriptive!