Reputation: 1709
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
}
Upvotes: 4
Views: 5453
Reputation: 133560
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.
Upvotes: 6
Reputation: 4291
Instead of defining the separate constructor, you are recommended to only have a parameter-less constructor and use the setArguments(Bundle)
method to pass data into the Fragment
. According to the documentation:
All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore.
Once you use setArguments(Bundle)
, you can call getArguments()
from inside the Fragment
to retrieve the data.
Upvotes: 1