Search code examples
javaandroidandroid-dialogfragment

Cannot create a default constructor from a class that extends DialogFragment and I have created my own custom constructor


I'm abit confused on an error message about default constructors.

I have 2classes MainActivity and ResultDialog. Some methods in MainActivity create a new dialog and pass 2strings to a custom constructor in ResultDialog.

ResultDialog extends DialogFragment. So I defined my own constructor but then when that error came up I just created a no arguments constructor and still that is not allowed.

I've searched abit on SO but the answers kind of explain that screen rotation may destroy and recreate the screen using the default constructor but still doesnt answer how I can solve that.

The error is Avoid non-default constructors in fragments:use a default constructor plus Fragment#setArguments(Bundle) instead

Someone please help me on this i'am a bit confused. Part of my ResultDialog class:

  public class ResultDialog extends DialogFragment {

private String message;//to hold the message to be displayed
private String title;//for alert dialog title

//constructor for the dialog passing along message to be displayed in the alert dialog
public ResultDialog(String message,String title){
    this.message = message;
    this.title = title;

}

public ResultDialog(){
    //default constructor
}

Solution

  • You can use newInstance. Check the docs

    http://developer.android.com/reference/android/app/Fragment.html

    Also check this

    Why do I want to avoid non-default constructors in fragments?

     ResultDialog rd = ResultDialog.newInstance("message","title");
    

    Then

      public static ResultDialog newInstance(String message,String title) {
        ResultDialog f = new ResultDialog();
        Bundle args = new Bundle();
        args.putString("message", message);
        args.putString("title", title);
        f.setArguments(args);
        return f;
    }
    

    And use getArguments() to retrieve values.

    String message = getArguments().getString("message");
    String title = getArguments().getString("title");
    

    getArguments()

    public final Bundle getArguments ()
    
    Added in API level 11
    Return the arguments supplied when the fragment was instantiated, if any.