Popup Error on blank EditText - java

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.

Related

How to disable positive button in onClick Function

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

How do I smoothly store user input data with EditText and RadioButtons (with a color set as well)?

I want to store the data from both the RadioButtons as well as the EditText values in the User attribute registeredData, but I don't know how to access my function in a way that allows me to grab all the data, as well as displaying a color change from the RadioButtons. Also how do I check if the input data is already in use (like email)?
I have tried splitting them into two different functions, but I can't get the data back from them into my User attribute registeredData. This is my first try at coding an app so any help is appreciated.
public class Registration extends AppCompatActivity {
private EditText displayname, email, password, confirmpassword;
private Button bsubmit;
private RadioGroup rgroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
displayname = findViewById(R.id.displayname);
email = findViewById(R.id.useremail);
password = findViewById(R.id.password);
confirmpassword = findViewById(R.id.confirmpassword);
bsubmit = findViewById(R.id.bsubmit);
rgroup = findViewById(R.id.rgroupteams);
bsubmit.setOnClickListener(onRegister);
}
private View.OnClickListener onRegister = new View.OnClickListener() {
#Override
public void onClick(View v) {
final User registeredData;
registeredData = new User();
switch (v.getId()) {
case R.id.bsubmit:
String useremail = email.getText().toString();
String userdisplayname = displayname.getText().toString();
String userpassword = password.getText().toString();
registeredData.email = useremail;
registeredData.displayname = userdisplayname;
registeredData.password = userpassword;
case R.id.rgroupteams:
RadioGroup group = findViewById(R.id.rgroupteams);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int idOfSelected) {
switch (idOfSelected) {
case R.id.rbtnmantis:
bsubmit.setBackgroundColor(Color.parseColor("#FF0000"));
bsubmit.setTextColor(Color.parseColor("#000000"));
registeredData.team = "Mantis";
break;
case R.id.rbtlightbringers:
bsubmit.setBackgroundColor(Color.parseColor("#F4DC00"));
bsubmit.setTextColor(Color.parseColor("#000000"));
registeredData.team = "LightBringers";
break;
case R.id.rbtncryptographers:
bsubmit.setBackgroundColor(Color.parseColor("#1C00AA"));
bsubmit.setTextColor(Color.parseColor("#FFFFFF"));
registeredData.team = "Cryptographers";
break;
default:
registeredData.team = "";
}
}
});
}
}
};
}
Right now the color change only turns on after I've have clicked the submit button because I don't know how to better set my setOnClickListener(), I haven't made use of any variables in the registeredData outside of this either, are they set up to be able to be accessed for some data (like displayname) to be displayed?
You need to move onCheckedChangeListener outside of onClickListener. Also, move registeredData outside onClickListener. Make sure that registeredData is "globally" accessible. Then on button click and checked listener you can set data from input fields and from checkboxes to the object.
Second, with TextUtils.isEmpty(email.getText().toString()) you can get boolean if email is empty or not. This you can use for other input fields, just send text to the isEmpty method

Android app crashes when trying to use variable [duplicate]

#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.screenlocked);
//Retrieve stored ID
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
LoginID = unique.getString("identifier", "");
//Retrieve stored phone number
final String phoneNumber = unique.getString("PhoneNumber", "");
phoneView = (TextView) findViewById(R.id.phone);
phoneView.setText(phoneNumber.toString());
//Retrieve user input
input = (EditText) findViewById(R.id.editText1);
userInput = input.getText().toString();
//Set login button
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
compareID();
}
});
}
public void compareID(){
if (userInput.equals(LoginID)){
//phone screen unlocked
//continue
Toast.makeText(ScreenLockActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else{
count += 1;
input.setText("");
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
}
}
I am developing a login activity and I would like to record down how many times the user tried to login, so every time there is a login attempt the count will increment by one... but when i run the activity, this error appears in my logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1,
Can someone help me solve this problem?
Here is your mistake:
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
the makeText you are trying to invoke here, is the makeText that takes as second parameter a resId. See here for more info. Since you want to print the count value, you have to convert it in a String.
String value = String.valueOf(count);
Toast.makeText(ScreenLockActivity.this, value, Toast.LENGTH_SHORT).show();
This line should be inside onClick() or compareID():
userInput = input.getText().toString();

EditText to Integer (Android)

I am attempting to convert an EditText, which is of type number in xml, to an Integer in order to calculate the value in seconds.
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
When I comment the lines where inHr and inMin are initialized I get no error in runtime, however when I leave the code as it is above I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{dit.assignment3/dit.assignment3.Timer}: java.lang.NumberFormatException: Invalid int: ""
I have also attempted this while getting the same error starting at the same line of code:
final CounterClass timer = new CounterClass(totalTime, 1000);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (hoursIn != null)
{
inHr = Integer.parseInt(hoursIn.getText().toString());
hoursMs = hrsToMs(inHr);
}
if (minIn != null)
{
inMin = Integer.parseInt(minIn.getText().toString());
minMs = minToMs(inMin);
}
else
{
textViewTime.setText("PLEASE GIVE A TIME");
}
totalTime = hoursMs + minMs;
timer.start();
}
});
Thanks in advance :)
I'm certain that this codes blocks are exactly same as you've shown here. That means You are directly initializing EditText and immediately calling getText() method which causes Exception.
There wont be any value immediately after initialization so that you are getting NumberFormatException when calling Integer.parseInt to empty value.
So I suggest you to put these codes inside some event like buttonClicked like here, so that you can be sure that you've entered some texts. And It's better checking if empty as well,
public void buttonClicked(View v){
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
}
You will get an java.lang.NumberFormatException: Invalid int: "" whenever you try to parse an empty string to Integer. Thus you need to check whether the EditText is empty or not.
You could easily do that as below
if (hoursIn.getText().toString().matches("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
OR
you can simply do a check as below
if (hoursIn.getText().toString().equals("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
First you have to put the lines where you are reading from edittext inside some event like click of a button. Then check whether anything is entered in the edittext or not, then use try/catch clause to convert it into number.
Try this code.
Add a button to your activity xml file:
<Button
android:height="wrap_content"
android:width="wrap_content"
android:onClick="myClickHandler" />
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
public void myClickHandler(View v){
if (hoursIn.getText().toString().matches("") || minIn.getText().toString().matches("")){
Toast.makeText(this, "You did not enter a text",Toast.LENGTH_SHORT).show();
return;
} else {
try {
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
Log.i("success");
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter number only",Toast.LENGTH_SHORT).show();
return;
}
}
}

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