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.stack.imgur.com/lbodG.png https://i.stack.imgur.com/nysfG.
Solution 1:
You must have a default constructor for Fragment.
publicclassTab1FragmentextendsFragment{
publicTab1Fragment(){
}
...
}
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:
publicclassTab1FragmentextendsFragment{
privatestaticfinalStringARG_URL="url";
publicTab1Fragment(){
}
publicstatic Tab1Fragment newInstance(String url) {
Tab1Fragmentfragment=newTab1Fragment();
Bundleargs=newBundle();
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");
Solution 2:
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
publicstatic MyFragment newInstance(String someData) {
MyFragmentfragment=newMyFragment ();
Bundleargs=newBundle();
args.putString("someData", someData);
fragment.setArguments(args);
return fragment;
}
and retrieve the data like this
@OverridepublicvoidonActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundleargs= getArguments();
StringsomeData="";
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);
Post a Comment for "Java.lang.runtimeexception: Unable To Start Activity Componentinfo, Unable To Instantiate Fragment, Could Not Find Fragment Constructor"