How to force a single line input in an Alert Dialog? - java

I have this AlertDialog showing up when the user presses the floating button. I don't want the user to be able to insert a multiple line input (i.e. ignoring her if she tries to press the enter key). How do I do this? Here's my code:
final EditText input = new EditText(getActivity());
new AlertDialog.Builder(getActivity()).setTitle("Package creation").setMessage("Insert package name:").setView(input).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
CharSequence toastText;
if (input.length() > 0) {
/* save the package name in the database */
toastText = getString(R.string.toast_package_saved);
} else toastText = getString(R.string.toast_empty_text);
Toast toast = Toast.makeText(getActivity(), toastText, Toast.LENGTH_SHORT);
toast.show();
input.getText().clear();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// do nothing
}
}).show();

In Xml
Put android:maxLines="1" in the EditText from the input xml layout.
Also choose an InputType, as Frédéric Letellier mentionated in his answer.
For example, android:inputType="phone"
More info in Specifying the Input Method Type
In Java
input.setMaxLines(1);
input.setInputType(InputType.TYPE_CLASS_PHONE);
In these examples, it is showed a setting for phone number. You can view the other types in InputType
ps: Also in xml, you can use android:singleLine="true", but this parameter is deprecated. So the first option sounds better.

Define the maximum of lines alone without changing inputType isn't enough
In your xml, to make it look like single line EditText :
android:maxLines="1"
And to prevent entering a new line :
android:inputType="text"
Which translates programmatically :
input.setMaxLines(1);
input.setInputType(InputType.TYPE_CLASS_TEXT);

Use below attribute for EditText i.e input View
android:ellipsize="end"

Related

I need to enable or disable the POSITIVE button of an AlertDialog based on input fields and dismiss only on good validation

I would like to enable or disable the OK (POSITIVE) button of the AlertDialog with a custom layout such that I can:
Disable the OK button initially
Enable the OK button when all required fields have been entered
Disable the OK button again if a required field has been cleared
Perform validation after the OK button is selected and prevent dismissal upon validation errors
Assume the AlertDialog layout is as follows with one required field description and one optional field age:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditText
android:id="#+id/description"
android:hint="Field is required"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/age" />
<EditText
android:id="#+id/age"
android:hint="Optional"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/description"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Assume I have a button to kick off the dialog
Button b = findViewById(R.id.main_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG,"button");
View viewcustom = getLayoutInflater().inflate(R.layout.customdialog,null);
EditText edt1 = viewcustom.findViewById(R.id.description);
EditText edt2 = viewcustom.findViewById(R.id.age);
// render alertdialog
}
});
Here is the code. I created a custom layout with 2 EditText fields and require only 1 to be entered. The first is treated as just text that must be present and the second is treated as an optional Age. The final example shows how to add validation and to "not dismiss" after OK is pressed and validation fails.
The OK button is initially disabled and when data is entered in the first text field the OK button is enabled.
By controlling the enable/disable of the positive (OK) button it requires the user to the enter fields necessary (rather than giving them an error when omitted).
Note that when the user clears the same field the OK button is disabled.
You can also add a hint to the EditText field(s) to indicate required (shown in second example).
Note that this was used as reference for the EditText listening (as I linked to in comment).
Finally, the last demo shows if you really wanted to show an error on field validation after the OK button is enabled and pressed. (From here.)
This should be obvious how to expand it to all your EditText fields. And bear in mind you can an condition to enabling the OK button - here it is just at least one character.
Button b = findViewById(R.id.main_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG,"button");
View viewcustom = getLayoutInflater().inflate(R.layout.customdialog,null);
EditText edt1 = viewcustom.findViewById(R.id.description);
EditText edt2 = viewcustom.findViewById(R.id.age);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this)
.setView(viewcustom)
.setPositiveButton("Ok", (dialogInterface, i) -> {
String d = edt1.getText().toString();
String a = edt2.getText().toString();
Toast.makeText(MainActivity.this,d, Toast.LENGTH_LONG).show();
});
alertDialog.setNegativeButton("Cancel", null);
AlertDialog ad = alertDialog.create();
edt1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence sequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence sequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
if (edt1.getText().length() > 0) {
// if user enters anything then enable - modify criteria as desired
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
} else {
// if user deletes entry then back to disabled
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
});
// Initially OK button is disabled.
ad.show();
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
});
And demo:
You can also add a hint to each field to indicate it is required if nothing is entered as in :
<EditText
android:id="#+id/description"
android:hint="Field is required"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/age" />
Finally, if you really, really want to allow the OK but then do further validation to display errors then add the following. Note that the second field is treated as an Age field and the data entered must be an integer. A bit contrived but used to show an example.
// add this after the AlertDialog create()
ad.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface anInterface) {
Button b = ad.getButton(DialogInterface.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do some validation on edit text
String s = edt2.getText().toString();
try {
Integer age = Integer.valueOf(s);
Toast.makeText(MainActivity.this,d+":"+age, Toast.LENGTH_LONG).show();
ad.dismiss();
} catch (Exception e) {
// complain
Toast.makeText(MainActivity.this, "Age must be an integer", Toast.LENGTH_LONG).show();
}
}
});
}
});
And demo of requiring the optional Age to be an integer:

Android: finding button by id

I have a problem with finding buttons. I have an AlertDialog where I choose one of 5 options. When I choose an option I want change the color of the button I clicked. I declared buttons in xml file inside <RealativeLayout> but when I'm trying to find my button by id (id's are like "id1","id2"...)using the findViewById method, there is a mistake, which says that I can't use this method like I do:
AlertDialog.Builder builder = new AlertDialog.Builder(StartGameActivity.this);
builder.setTitle(R.string.pickColor);
builder.setItems(R.array.colorArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Button btn_tmp;
String theButtonId = "id";
theButtonId = theButtonId+(String.valueOf(which));
btn_tmp = (Button) findViewById(theButtonId);
}
});
How can I fix that or maybe I should use other method?
EDIT:
I think I solved my problem. I used one of Button's method: getId() like this:
final int id = clickedButton.getId();
final ImageButton btn_tmp;
btn_tmp = (ImageButton)findViewById(id);
Background: IDs are esentially variables
In the XML files we give IDs to the resources, and then the compilers use all these to generate the gen/R.java. So essentially, these IDs are int variables belonging in class R.
An example of R.java:
// btw this file should never be edited!
public final class R {
public static final class id {
public static final int id1=0x7f0100aa;
public static final int id2=0x7f0100ab;
}
}
Just because a String exists that contains a valid name of a variable (R.id.id1), it can't magically access that variable. To do this, one can use reflection. However, in this case I believe it is an unnecessary complication, and will even be slower.
findViewById needs an ID (integer variable):
You cannot supply a String to this function. You should use an integer value, and specifically the ones that correspont to int variables in R.java.
For example:
findViewById(R.id.id1) // for your 1st button
Solution:
You can dynamically select the integer value:
AlertDialog.Builder builder = new AlertDialog.Builder(StartGameActivity.this);
builder.setTitle(R.string.pickColor);
builder.setItems(R.array.colorArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Button btn_tmp;
int chosenID=-1;
switch (which) {
case 1: chosenID=R.id.id1;
break;
case 2: chosenID=R.id.id2;
break;
}
btn_tmp = (Button) findViewById(chosenID);
}
});
It is also suggested to use more explanatory IDs, like: buttonDoThis, buttonDoThat.
btn_tmp = (Button)findViewById(R.id.YourButtonId);
You are passing string instead of integer.
If you are using your own layout.xml for the dialog, you need to inflate it first and give the view to your dialog builder.
LayoutInflater layoutInflater = (LayoutInflater) StartGameActivity.this.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
final RelativeLayout customDialogView= (RelativeLayout) layoutInflater.inflate(R.layout.custom_dialog_view, null);
AlertDialog.Builder builder = new AlertDialog.Builder(StartGameActivity.this);
builder.setTitle(R.string.pickColor);
//give the custom view to your dialog builder.
builder.setView(customDialogView);
builder.setItems(R.array.colorArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Button btn_tmp;
switch(which){
//....cases
case 1:
btn_tmp = (Button) customDialogView.findViewById(R.id.button1);
//set the color of the button selected
break;
case 2:
btn_tmp = (Button) customDialogView.findViewById(R.id.button2);
//set the color of the button selected
break;
}
//....cases
}
});
You are trying to use findViewById() with a String that holds the variable name of the ID. Java doesn't support this kind of dynamic variable names since variable names are only known at compile time, not run time. What are you trying to do? You will need to find another way to solve this problem. Please explain further and we can give suggestions.

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.

Android custom AlertDialog height not honoring layout parameters

So I am creating a custom AlertDialog using the Builder. I have a custom view I am inflating in the dialog with the following layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText android:id="#+id/edit_username"
style="#style/EditPassword"
android:hint="#string/login_username_hint" />
<EditText android:id="#+id/edit_password"
style="#style/EditPassword"
android:hint="#string/login_password_hint" />
</LinearLayout>
The android:layout_height style for the EditText controls is set to "wrap_content". When I show the dialog with this custom view the dialog is stretched to fill the height of the entire screen. No matter what I set the layout_height on the LinearLayout to (including hardcoded pixel values), it still fills the entire screen on my emulator.
I'm hoping there's something simple that I'm missing here?
EDIT: I looked in the Hierarchy Viewer and the layout I included in this question is correctly defined, but it is wrapped within a FrameLayout within a FrameLayout, and the outermost FrameLayout is set to "wrap_content" but is rendering in the Viewer with a bunch of empty space below it.
EDIT 2: As requested, the code that inflates the layout.
protected Dialog onCreateDialog(int id) {
switch(id) {
case AUTHENTICATION_DIALOG:
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
final View loginView = inflater.inflate(R.layout.login_dialog, null);
return new AlertDialog.Builder(HomeActivity.this)
.setTitle("Upload profile data")
.setView(loginView)
.setPositiveButton("Upload", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText userName = (EditText)loginView.findViewById(R.id.edit_username);
EditText password = (EditText)loginView.findViewById(R.id.edit_password);
String userNameStr = StringUtils.convertToTrimmedString(userName.getText());
String passwordStr = StringUtils.convertToTrimmedString(password.getText());
if (userNameStr.equals("") || passwordStr.equals("")) {
new AlertDialog.Builder(HomeActivity.this)
.setTitle("Required fields missing")
.setMessage("You must enter a username and password")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
HomeActivity.this.showDialog(AUTHENTICATION_DIALOG);
dialog.dismiss();
}
}).show();
} else {
dialog.dismiss();
} // end if user entered username and password
} // end "Upload" onClick
}) // end setPositiveButton DialogInterface.OnClickListener()
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
} // end "Cancel" onClick
}).create();
default:
return null;
}
}
So I switched to using a RelativeLayout like so:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText android:id="#+id/edit_username"
style="#style/EditPassword"
android:hint="#string/login_username_hint" />
<EditText android:id="#+id/edit_password"
style="#style/EditPassword"
android:layout_below="#+id/edit_username"
android:hint="#string/login_password_hint" />
</RelativeLayout>
and it works fine. I switched back to Linear to test and it exhibited the old broken behavior when I switched back to the LinearLayout. I'm going to leave this answer unmarked in the hopes that someone can tell me why it's freaking out over LinearLayout vs Relative.

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