Reputation: 818
An app crashed with the following msg:
android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment blabla.WelcomDialog: make sure class name exists, is public, and has an empty constructor that is public
It crashed on the emulator (running android 2.2) the first time i launched the app after installing it. When the app is launched, it does display a splash screen. If it is the first time, some background initialization is done while the splash screen is showing, otherwise, the splashscreen lasts 1.5 seconds. When the splash screen activity ends, it calls the main app activity. In the main activity onCreate() method, at the end, i show the WelcomeDialog:
new WelcomeDialog( this ).show( getSupportFragmentManager(), "");
the welcome dialog class is the following:
class WelcomeDialog extends SherlockDialogFragment//DialogFragment
{
MyApp activity;
/**
*
*/
public WelcomeDialog( MyApp activity )
{
super();
this.activity = activity;
}
@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
final View v = inflater.inflate( R.layout.welcome, container, false );
Button btn;
btn = (Button)v.findViewById( R.id.close_btn );
btn.setOnClickListener( new View.OnClickListener()
{
@Override
public void onClick( View view )
{
dismiss();
}
});
getDialog().getWindow().setBackgroundDrawableResource( R.color.transparent );
getDialog().getWindow().clearFlags( WindowManager.LayoutParams.FLAG_DIM_BEHIND );
getDialog().setCanceledOnTouchOutside( false );
return v;
}
/*
*
*/
public WelcomeDialog Show( FragmentManager fm )
{
show( fm, "" );
return this;
}
}
Now, i know that the dialog fragment should have only a constructor with no parameters and that you have to pass parameters using a Bundle object (and that there is a getActivity() method to retrieve the activity), but what bother me is that the app was launched for the first time. How it is possible that it gave that exception even if the fragment was never instantiated before (so not re-attaching was possible)? I want to make clear that this bug happened only one time (i installed/deleted the app a lot of times for debug purpose and it never occurred). Another question is: do i need to put the welcome dialog in a separate file? Thank you.
Upvotes: 0
Views: 115
Reputation: 1746
Fragments mustn't have a constructor. That is because of how the FragmentManager instantiates them. I suggest you remove the constructor completely and override the onAttach() method:
@Override
public void onAttach(Activity ac){
super.onAttach(ac);
this.activity = ac;
}
Upvotes: 2