Null Validation on EditText box in Alert Dialog - Android - java

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);

Related

how can i display a list of selected checkboxes in an alert dialog?

am trying to properly display a list of selected checkboxes stored in an array and display them as a list in an alert dialog.
if(registeredCourseList.getcoursessize() <= 5){
System.out.println(registeredCourseList.getCoursesArray());
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure you want to register the following courses? ");
// add a checkbox list
String[] courses ={String.valueOf(registeredCourseList.getCourses().toString())};
boolean[] checkedItems = {true, true, true, true, true};
builder.setMultiChoiceItems(courses, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// user checked or unchecked a box
}
});
// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// user clicked OK
// send the map or array to the server
try {
processRegistration(mView,registeredCourseList.getCoursesArray());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Context context = getApplicationContext();
CharSequence text = "Registered Courses Successfully";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
onBackPressed();
}
});
builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
} else {
Context context = getApplicationContext();
CharSequence text = "Choose at least 5 courses";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//back to the reg activity
// onBackPressed();
}
i can get the courses but they display and an array object. i want to display the courses as a list of checkeboxes in the alert dialog.
I have checked your code like this
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure you want to register the following courses? ");
// add a checkbox list
String[] courses ={"acx","sadsa","ksk","ksj","ywtgd"};
boolean[] checkedItems = {true, true, true, true, true};
builder.setMultiChoiceItems(courses, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// user checked or unchecked a box
}
});
builder.show();
and it is showing five different checkboxes. Check your String[] courses ={String.valueOf(registeredCourseList.getCourses().toString())};
I guess output of this line is all String Data at 0 index instead of showing on different indexes.
So instead of using above line Use for loop to insert values inside array
Edited for FOR Loop
Just an Example
ArrayList courses=new ArrayList();
for(int i=0;i<registeredCourseList.size;i++){
courses.add(registeredCourseList.get(i).getCourses());
}
Try something like this

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

EditText in DialogFragment always return empty string

I have implemented form in my dialog, and when positive button is clicked I create new object to ma database. I've created global variable for EditText's but still not work. Where I want get text value from them I always get empty string.
here is code:
EditText name, desc;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
view = inflater.inflate(R.layout.new_dialog, null);
name = (EditText) view.findViewById(R.id.workout_name);
desc = (EditText) view.findViewById(R.id.workout_description);
builder.setView(inflater.inflate(R.layout.new_dialog, null)).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MyDbHelper helper = new MyDbHelper (getActivity());
MyObj w = new MyObj ();
w.setName(name.getText().toString(););
w.setDescription(desc.getText().toString());
w.setLevel(1);
long id = helper.createWorkout(w);
Toast.makeText(getActivity(), id+"", Toast.LENGTH_LONG).show();
callback.onPositiveButtonClick();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
callback.onNegativeButtonClick();
}
});
return builder.create();
}
Any ideas please?
I stumbled upon the same issue. You can get the views inflated in the dialog using getDialog() provided by the onClick.
((EditText) getDialog().findViewById(R.id.your_editText_ID)).getText().toString()
In below code, you are inflating new_dialog layout and your name and desc EditTexts belong to this layout.
view = inflater.inflate(R.layout.new_dialog, null);
name = (EditText) view.findViewById(R.id.workout_name);
desc = (EditText) view.findViewById(R.id.workout_description);
But when you are setting the layout of the dialog you are setting new_workout_dialog. your name and desc do not belong to this layout.
builder.setView(inflater.inflate(R.layout.new_workout_dialog, null))
Furthermore, even if you used new_dialog while setting the builders view, name and desc would still be irrelevant. Because you are completely creating a new view inside setView method.
Use the view variable as following:
builder.setView(view, null))

How should I return to a previous dialog from another one?

I've got an inputDialog, which allows for some text inputs. On clicking save, the inputDialog checks if the entered text is already available (to prevent double entries). If this is the case, a new AlertDialog is created, simply stating "The value you entered already exists", with just an "Ok" button to dismiss this AlertDialog. This all works.
I would like to have the inputDialog pop back up again, after dismissing the AlertDialog, with the values that were entered by the user before still in the editText fields.
I'm not expecting any problems on getting those values back in the editText fields (Store them in a variable on clicking save, if the double entry error occurs, set those variables on the editText's. If I'm doing this in a stupid way, please let me know).
I am however having trouble with getting the first (inputDialog) dialog to come back. The code you see below is the code for my inputDialog fragment (The code is simplified, so if something seems to be missing, it probably is. Let me know, so I can add it back in.)
So, to repeat myself: How can I return to the previous dialog after dismissing the second one?
StuffManagerInputDialogFragment.java:
public class StuffManagerInputDialogFragment extends DialogFragment {
EditText nameInputField;
EditText tagInputField;
DBHandler dbHandler;
StuffManagerFragment f = new StuffManagerFragment();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v_iew = inflater.inflate(R.layout.fragment_inputdialog, null);
nameInputField = (EditText) v_iew.findViewById(R.id.inputdialogname);
tagInputField = (EditText) v_iew.findViewById(R.id.inputdialogtag);
dbHandler = new DBHandler(getActivity(), null, null, 1);
final MainActivity ma = (MainActivity) getActivity();
final AlertDialog.Builder newLinkDialog = new AlertDialog.Builder(getActivity());
newLinkDialog.setView(v_iew)
.setTitle("New Link")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String nameInputFieldText = nameInputField.getText().toString();
String tagInputFieldText = tagInputField.getText().toString();
ArrayList<String> nameArray = dbHandler.nameArrayMethod();
ArrayList<String> tagArray = dbHandler.tagArrayMethod();
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
if (nameArray.contains(nameInputFieldText) || tagArray.contains(tagInputFieldText)) {
if (nameArray.contains(nameInputFieldText) && tagArray.contains(tagInputFieldText)) {
AlertDialog.Builder errorBoth = new AlertDialog.Builder(getActivity())
.setTitle("Error")
.setMessage("The name and tag you entered are already in use.")
.setIcon(R.drawable.ic_error_black)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Return to previous dialog here
}
});
errorBoth.show();
}
} else {
dbHandler.addLink(nameInputFieldText, tagInputFieldText);
nameArray = dbHandler.nameArrayMethod();
int nameArraySize = (nameArray.size() - 1);
MenuItem item = menu.add(R.id.group1, nameArraySize, 1, nameArray.get(nameArraySize));
Toast.makeText(getContext(), "'" + nameInputFieldText + " - " + tagInputFieldText + "' link saved.", Toast.LENGTH_SHORT).show();
ma.addSMVFFragments();
f.hideDeleteAllButton = false;
getActivity().invalidateOptionsMenu();
}
}
})
.setNegativeButton("Cancel", null);
return newLinkDialog.create();
}
}
A better solution is to have a dialog fragment for your input layout, and that dialog fragment would display an AlertDialog on OK if the text validation fails. The input dialog fragment would not dismiss in this case, it will remain in the background so when you dismiss the alert dialog to tell the user the input is invalid, you return to the input dialog as it was.
To prevent the dialog fragment from dismissing on OK you would override onStart and get a reference to the OK button and set the listener there, like this:
#Override
public void onStart() {
super.onStart();
AlertDialog alertDialog = (AlertDialog) getDialog();
if (alertDialog != null) {
mOKButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
mOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (field OK) {
// save data
dismiss();
} else {
// show error dialog
}
}
});
}
}

Getting value from EditText within an AlertDialog Builder

Right, I know there's alot of similar questions. I've researched on stackoverflow as well as on the internet about this but still stumped.
This code is in a fragment.
...
private Context context = getActivity();
public void Dialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View mView = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(mView);
EditText a = (EditText) mView.findViewById(R.id.a);
EditText b = (EditText) mView.findViewById(R.id.b);
EditText c = (EditText) mView.findViewById(R.id.c);
//a.setText("abc");
//b.setText("xyz");
//c.setText("123");
strA = a.getText().toString();
strB = b.getText().toString();
final String strC = c.getText().toString();
}
This should be a typical approach to getting the view of the inflated layout and using it to access the elements inside the view, but it's not working no matter what I tried, I just could not get strA, strB and strC values using getText().toString().
//a.setText("abc");
//b.setText("xyz");
//c.setText("123");
But, if I uncomment the above 3 lines, the values get sent across. And I can receive them inside strA, strB, strC. Why is this so? I don't get it at all.
Any help greatly appreciated, thank you!
You are trying to get values at the time you initialize the dialog. you need to get values after an action, like a button click
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
strA = a.getText().toString();
strB = b.getText().toString();
}
});
Have a look at this display textview in alert dialog
Looks to me like you're checking the values of the EditTexts as soon as they're created. Which of course the value is going to be null every time since your user hasn't had time to type anything. I think you need a SubmitButton or something similar that checks the EditTexts in its onClickListener. Though I'll admit I've never inflated a view into an alert dialog.
Try like this.
MyDialogue is your Activity name.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MyDialogue.this);
// Get the layout inflater
LayoutInflater inflater = MyDialogue.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View mView = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(mView);
final EditText a = (EditText) mView.findViewById(R.id.a);
final EditText b = (EditText) mView.findViewById(R.id.b);
final EditText c = (EditText) mView.findViewById(R.id.c);
a.setText("abc");
b.setText("xyz");
c.setText("123");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String strA = a.getText().toString();
final String strB = b.getText().toString();
final String strC = c.getText().toString();
Log.e("tag", strA + " " + strB + " " + strC );
}
});
alertDialogBuilder.show();
The layout is not yet initiated when you are trying to set the values, you need to call AlertDialog alertDialog = alertDialogBuilder.create(); and then alertDialog.show(); or just alertDialogBuilder.show() before you can edit the textView content.

Categories

Resources