gordonwd
gordonwd

Reputation: 4587

Android Fragment Re-Instantiation Error

I thought I had my conversion to fragments pretty well done until I rotated the screen. I am getting the following types of errors:

RuntimeException: Unable to start activity ComponentInfo{com.ghcssoftware.gedstar/com.ghcssoftware.gedstar.GedStar}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.ghcssoftware.gedstar.PersonTab$PersonTabFrag: make sure class name exists, is public, and has an empty constructor that is public

The class in question does exist, is public, and I added an empty constructor with no change in the results. Looking at some sample code, I do notice some differences from the way my code is written, although I don't see empty constructors either:

1) Is there any reason that my fragment class should be declared "static" as many samples are?

2) Do I need to implement the use of "newInstance" within my fragment class? Why is this done instead of just having a constructor? For example from one of the V14 samples:

public static class CountingFragment extends Fragment {
    int mNum;

    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static CountingFragment newInstance(int num) {
        CountingFragment f = new CountingFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

I'm still a bit unfamiliar with some Java concepts, so may be missing something basic here.

Doug Gordon GHCS Software

Upvotes: 4

Views: 2419

Answers (2)

user622689
user622689

Reputation: 211

2). Passing a variable throw newInstance function argument, in your case it's num, allows to exclude class private variable that needed to bring value between constractor and onCreateView. For int variable it sove nothing, but for long string... regards, yury

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006644

Is there any reason that my fragment class should be declared "static" as many samples are?

Only if it is an inner class of something. Since yours appears to be an inner class of PersonTab, then it will need to be static. Or, move it outside of PersonTab to be a standalone Java class.

Do I need to implement the use of "newInstance" within my fragment class? Why is this done instead of just having a constructor?

It is just a factory method. It is not required by the framework.

Upvotes: 4

Related Questions