Kedarnath
Kedarnath

Reputation: 49

java.lang.RuntimeException: Unable to start activity ComponentInfo, Unable to instantiate fragment, could not find Fragment constructor

Please see all the four pictures, first 3 pictures has error screen, the last one has Fragment constructor.

https://i.sstatic.net/lbodG.png enter image description here

https://i.sstatic.net/nysfG.png enter image description here

https://i.sstatic.net/AHYCR.png enter image description here

https://i.sstatic.net/telPC.png enter image description here

Upvotes: 2

Views: 1985

Answers (2)

Man
Man

Reputation: 2817

You must have a default constructor for Fragment.

public class Tab1Fragment extends Fragment{

public Tab1Fragment(){
}
...
}

If you want to pass data to your fragment you must do that by setArguments(), not by passing it through constructor, not good practice. Instead try something like this:

public class Tab1Fragment extends Fragment{
    private static final String ARG_URL = "url";
    public Tab1Fragment(){
    }
    public static Tab1Fragment newInstance(String url) {
            Tab1Fragment fragment = new Tab1Fragment();
            Bundle args = new Bundle();
            args.putString(ARG_URL, url);
            fragment.setArguments(args);
            return fragment;
        }
}

And to get url value in fragment use

getArguments().getString(ARG_URL);

Now use newInstance method to get fragment instance.

Tab1Fragment.newInstance("your url");

Upvotes: 1

Tyler V
Tyler V

Reputation: 10910

As @Mangal mentioned, a Fragment must have a default (no argument) constructor. To pass data to a new fragment, use a static function, like this

public static MyFragment newInstance(String someData) {
    MyFragment fragment = new MyFragment ();
    Bundle args = new Bundle();
    args.putString("someData", someData);
    fragment.setArguments(args);
    return fragment;
}

and retrieve the data like this

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle args = getArguments();
    String someData = "";
    if( args != null ) {
        someData = args.getString("someData", "");
    }
}

Then, instead of calling

new MyFragment(data);

in the code where you create the Fragment, you would instead call

MyFragment.getInstance(data);

Upvotes: 1

Related Questions