Checking user input from Edit Text in Android - android

I am trying to build a small game app for a school project. It should consist of two edit text fields and a button. In the first field, there should be two randomly generated numbers by the app. In the second field, a user should enter the sum of those two numbers. If the sum is correct, a toast will be displayed when the user clicks the button, saying "You guessed it". If it's not correct, then the toast will say "You did something wrong".
The part with the random numbers is working just fine. However, I simply cannot make it check what the user has entered in the second field. And because of that I can't write any onClick method for the button that would check whether the user has entered the correct sum of those two random numbers or not.
Any help or suggestion would be much appreciated, thanks!

But you don't really need the TextWatcher for what you want to do.
Here's a simple guess-try of what you're trying to do.
theButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int number1, number2;
//figure out the numbers from the first edittext, i'm pressuming there's a space between the numbers
String[] parts = firstEditText.getText().toString().split(' ');
number1 = Integer.valueOf(parts[0]);
number2 = Integer.valueOf(parts[1]);
//now we know the numbers, lets Toast whether the user was right or wrong
int enteredNumber = Integer.valueOf(secondEditText.getText().toString());
if(enteredNumber == (number1 + number2) ) {
Toast.makeText(getActivity(), "You guessed it right!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Something's not right...", Toast.LENGTH_SHORT).show();
}
}
});

Related

How do I check if EditText has a value?

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.

How to use the Edittext in android

So I have 6 edit texts and a button as shown below:
My question is how do I use the input from the EditTexts (which I have stored in content_main.xml) to do mathematical operations like calculating an average which I want to show up in a toast when the calculate button is pressed. I have already written some code in the MainActivity.java file that brings up a toast when the calculate button is pressed (also in content_main.xml), I just need to figure out how to use the inputs from the EditTexts in the toast.
EditText myText // = findViewById...
String text = myText.getText().toString();
What you should do first is to give each of its elements ID to also recognize from the Activity.
Then you should use the click event of the button
//Here it is referring to the id that gave his element in its layout
Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
And finally, like the button, get their input values EditText
//Here it is referring to the id that gave his element in its layout
EditText text = (EditText)findViewById(R.id.editText01);
And in order to do math, parse the string value remaining on a double (double for decimals can give the exact calculation if you want something, if you want to be an int approximately)
try{
Double value = Double.parseDouble(text);
}catch(NumberFormatException e){
//Message for error parse
}

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.

Cannot convert EditText text to int

I'm trying to make a simple golf scoring app and I have encountered a problem when I'm trying to convert the number thats in the EditText where the user enters the par for the hole. The user can only enter numbers into the EditText. It doesn't show any errors and doesn't crash when I run it but it is obviously not getting a value from this code below no matter what is in the EditText. If I set the par to a number other than 0 it will effect the total score when the user goes to the next hole so that part of the code is working. Also when I move this code to another method other than onClick(View v) the app crashes. All help is appreciated.
public void onClick(View v){
if (parNum.getText().toString().equals("")){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please enter the par");
alert.show();
}
else {
//editvalue is a string that I declared but gave no value.
editvalue = parNum.getText().toString();
par = Integer.parseInt(editvalue);
}
}
You are checking not equals "". So please Remove ! Symbol from your if condition.
if (parNum.getText().toString().equals("")){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please enter the par");
alert.show();
}
else {
//editvalue is a string that I declared but gave no value.
editvalue = parNum.getText().toString();
par = Integer.parseInt(editvalue);
}
I hope this will help you.

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