How to disable positive button in onClick Function - java

I wanna disable positive button when one of input fields is empty.
I tried to use ((AlertDialog)dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
But it does not work.
new AlertDialog.Builder(MainActivity.this)
.setView(viewInput)
.setTitle("Add task")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String title = edtTitle.getText().toString();
String des = edtDes.getText().toString();
String date = edtDate.getText().toString();
String time = edtTime.getText().toString();
if(isEmpty(title) || isEmpty(des) || isEmpty(date) || isEmpty(time)){
((AlertDialog)dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
Toast.makeText(MainActivity.this,"Please, enter all fields.",Toast.LENGTH_SHORT).show();
}else{
Task task = new Task(title, des, date, time);
boolean isInserted = new TaskHandler(MainActivity.this).create(task);
if(isInserted){
Toast.makeText(MainActivity.this,"Task Saved",Toast.LENGTH_SHORT).show();
loadTasks();
}else{
Toast.makeText(MainActivity.this,"Unable to save",Toast.LENGTH_SHORT).show();
}
dialogInterface.cancel();
}
}
}).show();

You disable positive button after DialogInterface.OnClickListener. it means your positive button already set on your AlertDialog...
according to your need you have to disable positive button before you show dialog...
check this link...
Reference

Related

Change values of predefined Items in Multichoice AlertDialog

I have been trying to implement a multichoice alertdialog and for the most part everything is clear and understandable but the alertdialog gets the state of the items from a boolean array and all the items are set as true. I can't quite work out how I could change the state of an item in the array if it is checked in the alertdialog.
private void showCategorySelectionDialog() {
// Prepare the dialog by setting up a Builder.
final String selectionTitle = "Show on map: ";
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(selectionTitle);
final String[] categories = new String[]{"Camping grounds","Abandoned places","Nature areas","Lookout Points"};
// Find the current map type to pre-check the item representing the current state.
boolean[] checkedItems = new boolean[]{
true,
true,
true,
true
};
// Add an OnClickListener to the dialog, so that the selection will be handled.
builder.setMultiChoiceItems(
categories,
checkedItems,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
//check which item is clicked and if it was true then set it as false.
if (isChecked && checkedItems[which] == true){
checkedItems[which]= false;
}else{
//If item was clicked and the value was false then set it as true.
checkedItems[which] = true;
}
}
}
);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Build the dialog and show it.
AlertDialog categoryDialog = builder.create();
categoryDialog.setCanceledOnTouchOutside(true);
categoryDialog.show();
}
This current solution does not change values and my assumptions are that I am handling the Array in an incorrect way but I am not sure how the right way would be.
Since you want to change the value for an element in the array when it was checked then you can try to set the value to be equal with the isChecked variable that is passed through onClick() method.
Check the code below:
// Add an OnClickListener to the dialog, so that the selection will be handled.
builder.setMultiChoiceItems(
categories,
checkedItems,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
}
}
);

how to keep alert dialog open if user not provide the whole information

i have create a custom dialog where user will provide four information necessary from user , but if user click any button of alert dialog with out providing full information, the dialog is close, i want that alert not close unless the user provide full information
this is Custom alert dialog
enter image description here
this is java code for custom alert dialog
final ExtraFunction ef = new ExtraFunction(mContext);
final String PhoneNumber = holder.bdContactNumber.getText().toString();
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View promptsView = layoutInflater.inflate(R.layout.dialog_contact_for_blood, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setView(promptsView);
final EditText etSubject = (EditText) promptsView.findViewById(R.id.etSubject);
etSubject.setText(holder.bdBloodgroup.getText().toString());
final EditText etNumber_Bottles = (EditText) promptsView.findViewById(R.id.etNumber_Bottles);
final EditText etRequired_At = (EditText) promptsView.findViewById(R.id.etRequired_At);
final EditText etContact_number = (EditText) promptsView.findViewById(R.id.etContact_number);
alertDialogBuilder.setCancelable(false).setPositiveButton(R.string.send_message, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// get user input and set it to result
// edit text
String Subject = etSubject.getText().toString();
String Number_Bottles = etNumber_Bottles.getText().toString();
String Required_At = etRequired_At.getText().toString();
String Contact_number = etContact_number.getText().toString();
String blood_message = ""+Subject+" Blood "+Number_Bottles+" in Quantity is urgently required at "+Required_At+". Kindly contact at "+Contact_number+". Thanks.\n" + "("+R.string.app_name+")";
if(etNumber_Bottles.length()==0 && etRequired_At.length()==0 && etContact_number.length()==0)
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
else
{
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(PhoneNumber, null, blood_message, null, null);
Toast.makeText(mContext, R.string.success_message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, R.string.failed_message + PhoneNumber, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
// ef.SendSmsFunction(PhoneNumber,blood_message);
}
}).setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
i search but not clear about my problem
You did some wrong validation
if(etNumber_Bottles.length()==0 && etRequired_At.length()==0 && etContact_number.length()==0)
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
as this validation works only when all the field empty instead of && operator you should use OR operator and take the string value of editText dont use length value direct on edit text first type cast to string than get the length. You can take use length method or equals method for this like below.
You can use this.
if(etNumber_Bottles.getText().toString().tolength()==0 || etRequired_At.getText().toString().length()==0 || etContact_number.getText().toString().length()==0)
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
Or by equals method:
if(etNumber_Bottles.getText().toString().equals("") || etRequired_At.getText().toString().equals("") || etContact_number.getText().toString().equals(""))
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
setOnShowListener may solve your problem:
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Messsage")
.setPositiveButton(android.R.string.ok, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
Button buttonOk = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
if (buttonOk != null) {
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Write what you want to do on button click
}
});
}
}
});
Courtesy of this.
By the way, take a look on EditText#setError instead of yours Toast.makeText. Looks much more pretty!
P.P.S. I have changed my answer. You have to create AlertDialog and define setOnShowListener and your dialog will not closed on the button click. Is it what you desire?
Bro you need to learn how to validate view look at this example -https://stacktips.com/tutorials/android/edittext-validation-in-android-example
and https://www.excella.com/insights/how-do-i-validate-an-android-form and https://stackoverflow.com/a/33072633/4741746
there are some library provide easy way of validation one you can prefer is https://github.com/ragunathjawahar/android-saripaar
Best of luck

How to set checkbox checked and disabled

I have this code for showing list of languages for download:
public void onCreateDialog(ArrayList<String>fullLangArray, final ArrayList<String>codeLangArray) {
final String[] items = fullLangArray.toArray(new String[fullLangArray.size()]);
final ArrayList mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the dialog title
builder.setTitle("Updates...")
.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(Utils.SERVER_ADDRESS + "/" + codeLangArray.get(indexSelected) + ".zip");
} else if (mSelectedItems.contains(indexSelected)) {
mSelectedItems.remove(Integer.valueOf(indexSelected));
}
}
})
.setPositiveButton("Download", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
DownloadTask downloadTask = new DownloadTask(MainActivity.this);
downloadTask.execute(mSelectedItems.toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
I want to make a one item of a checkbox is checked and "disabled" like in a photo (Option 3) when AlertDialog is loaded.
Can you help me how to do it?
You can check the checkbox by using the setChecked() method which boolean value as parameter.
Example:
option1.setChecked(true);
and also uncheck it using
option2.setChecked(false);
If you want to set it to checked and disabled you have use setEnabled() which takes boolean as it's parameters.
Example.
option3.setChecked(true);
option3.setEnabled(false);
This will disable your checkbox and even check it. I hope this was helpful. ThankYou.
For setting Opacity
mSelectedItems.getBackground().setAlpha(128);
Where the INT ranges from 0 (fully transparent) to 255 (fully opaque).
For setChecked item
mSelectedItems.setChecked(true);
Disable checking
mSelectedItems.setEnabled(false)

Popup Error on blank EditText

How do I require the user to input data into an EditText and not allow the application to proceed until the EditText is populated?
Right now, my application continues to progress even after the user acknowledges the error message stating the EditText is empty and is required.
private final static int EMPTY_TEXT_ALERT = 0;
protected Dialog onCreateDialog(int id) {
switch(id) {
case EMPTY_TEXT_ALERT: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("oops!!")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
return null;
}
public void sends(View v) {
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
int year = datePicker.getYear();
int month = datePicker.getMonth();
int day = datePicker.getDayOfMonth();
final EditText phone = (EditText) findViewById(R.id.editText2);
final EditText nameplate = (EditText) findViewById(R.id.editText3);
final EditText issue = (EditText) findViewById(R.id.editText4);
String ph = phone.getText().toString();
if(ph.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
String np = nameplate.getText().toString();
if(np.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
String i = issue.getText().toString();
if(i.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
else
{StringBuilder s= new StringBuilder(100);
s.append(year);
s.append(". ");
s.append(month+1);// month starts from 0 in this
s.append(". ");
s.append(day);
s.append(". ");
s.append(". ");
s.append(ph);
s.append(". ");
s.append(np);
s.append(". ");
s.append(i);
String st=s.toString();
Intent emailIntentt = new Intent(android.content.Intent.ACTION_SEND);
emailIntentt.setType("plain/text");
String aEmailList[] = { "shreyas.t#gmail.com" };
emailIntentt.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
emailIntentt.putExtra(android.content.Intent.EXTRA_SUBJECT, "Feedback");
emailIntentt.putExtra(android.content.Intent.EXTRA_TEXT, st);
startActivity(emailIntentt);
}
}}
You can add return statement after showing the dialog as shown below.
if(i.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
return;
}
It would be better to use Toast messages than showDialog though.
I don't know how you are calling your sends() method, but after any empty error you can just add a return statement immediately after the showDialog(). It means that somehow the sends() method has to get re-invoked via the UI after the user has put in text.
If your sends() method is called from a button via onClick(), then it means the user will see dialog with error, input some text and then, hit the button to send again.
Shreyas Tallani
how to validate the phone number... enters more than 10 digits the
error message should be displayed
If you are just wanting to test the length of the String, just get the String and compare the length to the max length of 10.
In your validate(...) method do something similar to the following:
String ph = phone.getText().toString();
if(ph.trim().equals("")) {
showDialog(EMPTY_TEXT_ALERT);
} else if (ph.length() > 10) {
showDialog(TEXT_TOO_LONG_ALERT);
}
You could also make your EditText only allow numeric values. This would help you validate the numbers. You can do this in the xml file or in code.
xml
android:inputType="TYPE_NUMBER_VARIATION_NORMAL"
code
EditText.setInputType(InputType.TYPE_NUMBER_VARIATION_NORMAL);
First thing you can do, is add a validate(...) method. Inside validate(...), you need to validate all the fields and if anything is left blank then show the error message and stop app progression.
If all the fields are fine, then call your send method. And send(...) should only be sending your data, not checking validation.

Null Validation on EditText box in Alert Dialog - Android

I am trying to add some text validation to an edit text field located within an alert dialog box. It prompts a user to enter in a name.
I want to add some validation so that if what they have entered is blank or null, it does not do anything apart from creating a Toast saying error.
So far I have:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
But this just closes the Alert Dialog and then displays the Toast. I want the Alert Dialog to still be on the screen.
Thanks
I think you should recreate the Dialog, as it seems the DialogInterface given as a parameter in onClick() doesn't give you an option to stop the closure of the Dialog.
I also have a couple of tips for you:
Try using Activity.onCreateDialog(), Activity.onPrepareDialog() and of course Activity.showDialog(). They make dialog usage much easier (atleast for me), also dialog usage looks more like menu usage. Using these methods, you will also be able to more easilty show the dialog again.
I want to give you a tip. It's not an answer to your question, but doing this in an answer is much more readable.
Instead of holding a reference to an AlertDialog.Builder() object, you can simply do:
new AlertDialog.Builder(this)
.setTitle("Record New Track")
.setMessage("Please Name Your Track:")
//and some more method calls
.create();
//or .show();
Saves you a reference and a lot of typing ;). (almost?) All methods of AlertDialog.Builder return an AlertDialog.Builder object, which you can directly call a method on.
The same goes for Toasts:
Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show();
I make a new method inside my class that shows the alert and put all the code for creating the alert in that one method. then after calling the Toast I call that method. Say I named that method createAlert(), then I have,
createAlert(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
createAlert();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
}
What you should do is to create a custom xml layout including a textbox and an Ok button instead of using .setPositiveButton.
Then you can add a click listener to your button in order to validate the data and dismiss the dialog.
It should be used in CreateDialog:
protected Dialog onCreateDialog(int id)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (id==EDIT_DIALOG)
{
final View layout = inflater.inflate(R.layout.edit_dialog, (ViewGroup) findViewById(R.id.Layout_Edit));
final Button okButton=(Button) layout.findViewById(R.id.Button_OkTrack);
final EditText name=(EditText) layout.findViewById(R.id.EditText_Name);
okButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
String textString = trackName.getText().toString();
if (textString != null && textString.trim().length() ==0)
{
Toast.makeText(getApplicationContext(), "Please enter...", Toast.LENGTH_LONG).show();
} else
removeDialog(DIALOG_EDITTRACK);
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Edit text");
AlertDialog submitDialog = builder.create();
return submitDialog;
}
Even though it's an old post, the code below will help somebody. I used a customized layout and extended DialogFragment class.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.Name_of_the_customized_layout, null);
final EditText etxtChamp = view.findViewById(R.id.editText);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Enter a Name")
.setTitle("Mandatory field ex.");
builder.setView(view);
final Button btnOk = view.findViewById(R.id.ok);
final Button btnCancel = view.findViewById(R.id.cancel);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(etxtChamp.getText().toString().isEmpty()){
etxtChamp.setError("Oups! ce champ est obligatoire!");
}else{
//Get the editText content and do whatever you want
String messageEditText = etxtChamp.getText().toString();
dismiss();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
Use This code for displaying Dialog.
public void onClick(DialogInterface dialog, int whichButton) {
String textSt`enter code here`ring = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("please enter valid field")
.setPositiveButton("OK", null).show();
}
This will create a Dialog for you, editText is empty or what are conditions you wants.
//if view is not instantiated,it always returns null for edittext values.
View v = inflater.inflate(R.layout.new_location_dialog, null);
builder.setView(v);
final EditText titleBox = (EditText)v.findViewById(R.id.title);
final EditText descriptionBox = (EditText)v.findViewById(R.id.description);

Categories

Resources