Related Posts
- How to Avoid NullPointerException in Java Part 1
- How to Avoid NullPointerException in Java Part 2
- Avoid Call Instance Method in Constructor to Prevent NullPointerException
Avoid Call Instance Method in Constructor
Calling am instance method while the object is being constructed is anti-pattern and error prone, can easily lead to bugs.
public class MyDialog extends Dialog {
private final TextView bodyText;
public MyDialog(Context context) {
super(context);
setContentView(R.layout.dialog);
findViewById(R.id.text);
bodyText =
}
public void setText( CharSequence text) {
setText(text);
bodyText.
}
public CharSequence getProgressBarText() {
return bodyText.getText();
} }
Checker framework would report error like below:
error: [method.invocation.invalid] call to setContentView(int) not allowed on the given receiver.
setContentView(R.layout.dialog);
^
found : @UnderInitialization(android.app.Dialog.class) @NonNull Dialog
required: @Initialized @NonNull Dialog
MyDialog.java error: [method.invocation.invalid] call to <T>findViewById(int) not allowed on the given receiver.
bodyText = findViewById(R.idtext);
^
found : @UnderInitialization(android.app.Dialog.class) @NonNull Dialog
required: @Initialized @NonNull Dialog
This can be fixed:
public class MyDialog extends Dialog {
public static MyDialog newInstance(Context context) {
View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog, null);
new MyDialog(context, dialogView);
MyDialog dialog = setUp(dialogView);
dialog.return dialog;
}
private final TextView bodyText;
private CarProgressDialog(Context context, View dialogView) {
super(context);
checkNotNull(dialogView.findViewById(R.id.text));
bodyText = Preconditions.
}
public void setProgressBarText(CharSequence text) {
setText(text);
bodyText.
}
public CharSequence getProgressBarText() {
return bodyText.getText();
} }
Another approach:
public class MyDialog extends Dialog {
private CharSequence text;
@MonotonicNonNull private TextView bodyText;
public MyDialog(Context context) {
super(context);
this.text = "";
}public MyDialog(Context context, CharSequence text) {
super(context);
this.text = text;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
findViewById(R.id.text);
bodyText = setText(text);
bodyText.
}
public void setText(CharSequence text) {
this.text = text;
if (bodyText != null) {
setText(text);
bodyText.
}
}
public CharSequence getText() {
return text;
} }