Cannot convert EditText text to int - android

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.

Related

Checking user input from Edit Text in 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();
}
}
});

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.

EditText.setText() not working & getting wrong values from EditText

I'm a starter on Android, mocking a contact list of a phone. Now I have a contact list, like the pic below, when I press the one item of the contact list, it pops up a dialog with two choices. And if I choose "Add to Black", another AlertDialog allows me to put this number to the blacklist. What I want to realize here is to automatically read the number of the item I picked, show it in the "number" blank, which doesn't require users to input again. But it turned out it didn't work, still nothing in the blank. The screenshots and codes of showing the add-black-dialog are below.
final View view = getLayoutInflater().inflate(R.layout.add_person, null);
AlertDialog alertDialog = new AlertDialog.Builder(MyTabHost.this).setTitle("Add a Black Number")
.setView(view).setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText inputNumber = (EditText) view.findViewById(R.id.inputNumber);
EditText inputRemark = (EditText) view.findViewById(R.id.inputRemark);
inputNumber.setText(dataList.get(arg2).get("number"));
String number = inputNumber.getText().toString();
String remark = inputRemark.getText().toString();
Map<String, String> map = new HashMap<String, String>();
map.put("remark", remark);
map.put("number", number);
map.put("display", Utils.formatPhoneNumber(number));
if (MyTabHost.blackList.get(0).containsValue("You don't have any black number")) {
MyTabHost.blackList.removeAll(MyTabHost.blackList);
}
MyTabHost.blackList.add(map);
int i = mySharedPreference.getBlackSize() + 1;
mySharedPreference.saveBlack(remark, number, i);
mySharedPreference.saveBlackSize(i);
dialog.dismiss();
new AlertDialog.Builder(MyTabHost.this)
.setMessage("Black number succesfully added")
.setPositiveButton("OK", null).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
alertDialog.show();
Actually I'm thinking whether I am using wrong view. As the codes state above, I use final View view = getLayoutInflater().inflate(R.layout.add_person, null);to get the new view of the dialog, which add_person.xml here is my layout.
The reason why I wondering about the wrong view is that something weirder happened: when I manually inputed the number and remark(say I pressed the contact "Jack"'s number:8871203459 and "Jack" as a remark) and pressed "Add", meanwhile the things in the blanks suddenly change to some numbers else(some numbers I got in other activities), like below, and the black data stored was also the odd wrong number.
That's odd because I did write the codes of getText(), and saved it:
EditText inputNumber = (EditText) view.findViewById(R.id.inputNumber);
EditText inputRemark = (EditText) view.findViewById(R.id.inputRemark);
inputNumber.setText(dataList.get(arg2).get("number"));
String number = inputNumber.getText().toString();
String remark = inputRemark.getText().toString();
Map<String, String> map = new HashMap<String, String>();
map.put("remark", remark);
map.put("number", number);
map.put("display", Utils.formatPhoneNumber(number));
This is a long and boring problem. Thanks for your reading and help...
Just moved relevant comment down into an answer.
That setText is only being run once you click the add button on your dialog. Move both find views and the setText out of the dialogs on click
use toString() Method for converting text into string and then place it in appropriate place. I faced a same problem and solved by this method.
I solved my second problem in this post. It was a careless mistaken by querying wrong ArrayList. This time the odd numbers don't exist. But the EditText is still not able to show the characters with what I want. Pls help if possible.
Update: I've found that though the EditView is not able to set the values visible to the users, it does get the value - I've tested that. What's odd is, whatever I input in the two blanks(should have shown the values) and press "Add" button, the app will always save the original value I try to let them show.
Specifically:
EditText inputNumber = (EditText) view.findViewById(R.id.inputNumber);
EditText inputRemark = (EditText) view.findViewById(R.id.inputRemark);
inputNumber.setText(contactList.get(arg2).get("number").toString());
inputRemark.setText(contactList.get(arg2).get("name").toString());
String number = inputNumber.getText().toString();
String remark = inputRemark.getText().toString();
Map<String, String> map = new HashMap<String, String>();
map.put("remark", remark);
map.put("number", number);
My EditTexts are able to get the contactList.get(arg2).get("number").toString() and contactList.get(arg2).get("name").toString(), but just don't show them. And whatever else I input on the EditTexts, they will pass the two values above, instead of what I newly input, though I've specified String number = inputNumber.getText().toString() and String remark = inputRemark.getText().toString().
Finally update: Problem solved, it's not a hard tech one but a programming logical mistake. Please refer to #ElefantPhace's answer on the upper side if any one encounters same problem. Thanks all!

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
}
}
}

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