0

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.

larsien
  • 109
  • 10
  • This error is not always producing. Very rarely reproducing. – larsien May 09 '14 at 02:20
  • Post your class declaration, too, i.e. the `public (static) class HelpFragment extends Fragment` and where it is in your code (e.g. if it's an inner class). – laalto May 13 '14 at 07:58

3 Answers3

0

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 already have onCreateView() in code. In normal situation, this code is working correctly. I'm sorry but your thinking is not correct. In result of searched in Stackoverflow.com, This error is about constructor and newInstance() method of Fragment. – larsien May 09 '14 at 04:26
0

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.

larsien
  • 109
  • 10
0

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;
}
LR89
  • 397
  • 1
  • 4
  • 14
  • Hi, LR89. Could you tell me why constructor should be static? As I know, static inner class is used to performance. So I think make inner class static is not necessary. – larsien May 13 '14 at 11:13
  • This is not a constructor, but a method that provides ability to pass arguments to fragment without overriding constructor. Why can't we simply override constructor? Check this answer http://stackoverflow.com/a/10450535/3519587 Why is this method static? Because... why not? It's not related with object instance, so there's no need to make it non-static. – LR89 May 13 '14 at 11:37