Dialog And Edittext Listener: Crash At Setenabled
Solution 1:
The scope of if and else is only upto next statment. If you want to use more than one statement than enclose it in block. For example-
else
{
button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(false);
}
Solution 2:
@Happy_New_Year is right. You are missing {} in else parts. If you don't put {}, then the only very next statement would be considered as the else part. The button.setEnabled(false);
is outside of else block. So the button
object is not being initialized here.
Solution 3:
Problem is at text = mEditText.getText().toString();
when text is null
null.toString();
will crash.
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
if (s != null)
{
if (s.length() > 0)
{
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);
}
else {
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
}
}
Here is entire code that I used in my project
AlertDialog.Builder builder; // Declare Globally
AlertDialog dialog; // Declare Globally
builder = newAlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Add New Keyword");
finalEditTextinput=newEditText(this);
input.setHint("Min 3 Chars");
builder.setView(input);
input.addTextChangedListener(newTextWatcher() {
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
if (s != null)
{
if (s.length() > 2)
{
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);
}
else {
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
}
}
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@OverridepublicvoidafterTextChanged(Editable s) {
}
});
builder.setPositiveButton(android.R.string.ok, newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int whichButton) {
if (input != null)
{
System.out.println("Entered Text" + input.getText().toString().trim());
}
}
});
builder.setNegativeButton(android.R.string.cancel, newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
Solution 4:
The error is obviously in this line :-
mEditText = new EditText(mContext);
By doing this, you have created a new object for an Edittext. We do such thing when we create a dynamic edittext or any other widget.
In a normal scenario, you need to pass a reference to your edittext which you must have given in a property called as "id" in an xml file for the edittext for example :-
<EditText
android:id = "@+id/editText1"
<!-- other properties-->
</EditText
and in your class, you need to do like this firstly :- mEditText = (EditText)findViewById(R.id.editText1);
I hope you got it now
Post a Comment for "Dialog And Edittext Listener: Crash At Setenabled"