简体   繁体   中英

I have added empty constructor in Fragment. but still “make sure class name exists, is public, and has an empty constructor that is public”

I have a question. I was coding some help pages using Fragment.

public HelpFragment(int i) {
            Bundle args = new Bundle();
            args.putInt("page", i);
            setArguments(args);
        }

In test case, I got this error.

"make sure class name exists, is public, and has an empty constructor that is public"

So that, I added empty constructor.

public HelpFragment() {
            Bundle args = new Bundle();
            args.putInt("page", 0);
            setArguments(args);
        }

But still that error is producing. What should do I? Thanks in advance.

how you call your fragment to your application? I think you SHOULD NOT override the constructor if you use fragment, and put your arguments in onCreate or onCreateView instead

if you use fragment i think onCreateView is better

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //your arguments here
    return inflater.inflate(R.layout.fragment_help_layout, container, false);
}

I'm totally stupid. I have been missing add this in code.

super()

But I don't 100% trust about this solution. I'll report if I see this error in Google Play crashes.

Don't override constructor at all. Instead create public static method:

public static HelpFragment newInstance(int i) {
    HelpFragment f = new HelpFragment();
    Bundle args = new Bundle();
    args.putInt("page", i);
    f.setArguments(args);
    return f;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM