How do I check if EditText has a value? - android

I have an EditText and a Button.
I want if an EditText was empty when clicked on my Button. I want to show message as a toast, like "please enter a number".

You can do something like this:
boolean hasValue = editText.getText().length() > 0;
or
boolean hasValue = !editText.getText().toString().isEmpty();
or to make sure it doesn't contain only spaces:
boolean hasValue = !editText.getText().toString().trim().isEmpty();

The cleanest way to do this is TextUtils.isEmpty(editText.getText())
The reason I say this is the cleanest way is because:
You avoid pointless conversion between CharSequence and String. Which creates an object. editText.getText() returns Editable, calling toString() creates an additional object which is not good. This method will also never return null in my experience.
You get a null and a length check out of that. If you look at the code for TextUtils.isEmpty(), it basically checks if the CharSequence is null and length is zero.
It avoids code duplication and the same method can be used with Strings or CharSequence objects and Editable is an implementation of CharSequence.
It's provided as part of the Android framework.
If you want to check the length of the trimmed String. Then use:
TextUtils.isEmpty(editText.getText())
&& TextUtils.getTrimmedLength(editText.getText()) == 0
If you want, you can create your own utility method to do this so you don't have to add such a long condition in your code repeatedly.
I would attached an OnFocusChangeListener to your EditText to check the change in value or a TextWatcher or both depending on how critical your requirement is. If your field had focus and lost it, do your validation with the OnFocusChangeListener, if your field has focus and the user is typing and delete the content or the content is too short, use TextWatcher to let them know.

Use this on click of your button:
EditText editText = (EditText) view.findViewById(EditTextID);
if(editText.getText().toString().length()==0) {
Toast alert = Toast.makeText(context, toast_message, Toast.LENGTH_SHORT);
alert.show();
}

In the onClickListener() of the button:
int length = editText.getText().length();
if(length == 0)
{
Toast.makeText(getActivity(), "Please enter a number",Toast.LENGTH_LONG).show();
}

you probably already found your answer, but for the ones who came here hoping to find an answer here is how its done:
you have to make a String object or Int object first then in your button function Click write this:
#Override
public void onClick(View view) {
String numberValue;
numberValue = yourEditText.getText().toString();
if (emailEtValue.matches("")){
Snackbar sbEmptyValue = Snackbar.make(view, "You must enter an Integer Value", Snackbar.LENGTH_LONG);
sbEmptyValue.show();
} else {
//DO THE THING YOU WANT
}
}
you can also use Toast but i prefer Snackbar because its cooler than Toast.

Related

How to make a button give different results everytime when user tap it?

I have a button and I want it to change the text that I positioned above the button to something random everytime the user press it. How can I do it?
I want to look something like this:
"Hello"
**press**
"Why did you press?"
**press**
"Don't do that again, or..."
**press**
"You just did!"
Here is the code of the button and the text.
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
textChange.setText(string.textChange2);
}
}
);
There is no magical way to have it randomly change the text, you have to program it to do that. You are going to have to create an array of responses and then in the button's code, tell it to cycle through those responses. So for example:
private String[] responseArray = {"Hello", "Why did you press?", "Don't do that Again", "You Just did!" }
private int numTimesPressed = 0
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
//note this line will cause an error if there is not enough values in the array. You would have to write a catch for this
textChange.setText(responseArray[numTimesPressed++]);
//if you want random, you'll have to change the array index you are accessing to random value between the array's bounds
}
}
);
You'll definitely need an array of string responses. Afterwards, the first approach I would use is to use a random number generator, and then just link it back to your array. Unfortunately I'm not able to write the code, since I don't know the exact syntax, but in pseudocode:
string array[x]={"Hello","Why did you press?",...};//Number of string responses (in this case it's 4)
int random_number;
random_number=RandomNumberGenerator(1,x);//1 and x are the lower and upper bounds
switch (random_number)://If you don't know, switch is basically a simplified if-else system
case 1:print "Hello";
.........
There are many random number generators online that you can use, depending on the language. Hope this helped!
P.S: Maybe you'll want to fine-tune your responses to make them more natural. For example, you probably want to re-roll your response if you get two of the same one in a row.

checking for empty values in textfield and spinner

Button btnSearch = (Button) pnlView.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener() {#
Override
public void onClick(View v) {
results.clear();
if (txtPatientID.getText().equals("") && txtFirstName.getText().equals("")
&& txtLastName.getText().equals("") && txtDOB.getText().equals("")
&& cboGender.getSelectedItem().equals("")) {
Toast.makeText(getActivity(),
"No criteria added", Toast.LENGTH_LONG).show();
return;
}
new Async().execute();
}
});
I have four text field and a spinner, when the user clicks search button, i need to display a message saying no criteria added. Its working, but i am not sure whether i am following the right approach in checking for empty value in textfield and spinner.
You should check the length instead of comparing with empty value. Because it will fail in one or more cases. you should check like this
if(txtPatientID.getText().toString().trim().length()==0)
trim() method will remove one or more spaces in your text
This seems okay. But you can trim() the getText() results to handle empty space characters.

How do I make a button execute code only if text is entered in a field?

I'm making an app for Android, and if you click the calculate button on one of the pages, without anything entered in the text boxes, it force closes. Some users were wondering if this could be fixed, so I was wondering if there was a way to make the onClickListener execute only if there is something inside the EditText.
You have to check it yourseft, such as:
final EditText editText = ...; // your edit
// check in your onClickListener
if (editText.getText().toString().isEmpty){ // Check if your EditText is
}else{ // If your EditTexit is not null
}
Please, search google before asking any question!
You can try following code,
suppose you have a EditText txtNum1 & txtNum2 , so onClickListener() method you can write following condition
public void onClick(View v)
{
if ( v == cmdCalculate )
{
if ( !txtNum1.getText().equals("") && !txtNum2.getText().equals("") )
{
// your calculation code
}
else
{
// post error msg code
}
}
}

How to allow only a valid floating point number into a text field in android

How to allow only a valid floating point number into a text field floating point like these only
2.353
-2.354
4444.45
Implement a focus listener on the field. When the focus changes from the textfield to any other part of your form simply use a regexp to check the validity of the input.
Something like :
^(-)?\d*(\.\d*)?$
Should do the trick.
Then use the pattern matching of Android to see if the input matches the regexp :
Pattern p = Pattern.compile("^(-)?\d*(\.\d*)?$");
Matcher m = p.matcher(inputString);
if (m.find()) {
////Found
}
else {
//Not found
}
But be aware of local settings...In France for example, the dot(.) used to separate the decimals is in fact a comma(,)
Use OnFocusChangeListener to achieve this.
//value pool
final String[] check = new String[]{"2.353","-2.354","4444.45"};
yourEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
String s = ((EditText)v).getText().toString().trim();
for(String tmp : check){
if(!TextUtils.isEmpty(s) && s.equals(tmp)){
//it ok
break;
}
else{
//do something
}
}
}
});
For edittext use android:inputType="number"
Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())`).
android:inputType="numberDecimal|numberSigned"

Toast message requiring user to fill in blank "EditText" fields

I am trying to get a message to appear when a button is clicked to tell the user to fill in the blank field. Currently, if the field is blank, it crashes/force closes the app. I tried to do the following code and had zero success. Originally I didn't have the if/else in there, I just ran the calculator(); method and the following imm code.
Could someone point me into the right direction?
public void onClick(View v)
{
if ((EditText)findViewById(R.id.amount1)== null)
{
Context context = getApplicationContext();
CharSequence text = "Enter a number";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
calculator();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
Im pretty sure this is the bad code:
if ((EditText)findViewById(R.id.amount1)== null)
Just dont know how to word it the way I want.
Try checking the length of the text in the EditText widget
EditText e = (EditText)findViewById(R.id.amount1));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}
Use this code.
EditText et = (EditText)findViewById(R.id.amount1));
if(et1.getText().length() == 0){
//Display toast here
} else{
//Your code
}
EditText text = (EditText)findViewById(R.id.amount1);
if(TextUtils.isEmpty(text.toString())) {
// show toast
}
Even if the field is blank, the edittext is not null. Use:
EditText editText = (EditText)findViewById(R.id.amount1);
String text = new String(editText.getText());
if (test.equals("")) {
//...
((EditText)findViewById(R.id.amount1)== null is just getting a reference to the EditText with the id amount1, it is not checking to see if that EditText has a valid entry.
To see if the EditText has text, you can get the String it holds by via EditText#getText().toString()
To make this work, first store the reference to the EditText in a var, then perform your checks on the String:
EditText et = (EditText)findViewById(R.id.amount1);
String amount1 = et.getText().toString();
if (amount1.equals("")) {
// Do your stuff here
}
I'm using local variables and just assuming you want the string to have content. You will likely need to do other checks to handle all the cases (like malformed input). Some of this you can reduce by setting the inputType on the EditText. For example, you might set it to numberDecimal if you are trying to handle only decimal numbers.
You actually want to check if the contents of the EditText are null or an empty string.
The line in question should look something like this:
if("".equals(((EditText)findViewById(R.id.amount1)).getText().toString()))
Of course you may want to break that statement up into more lines to make it a bit more readable!

Categories

Resources