Android AlertDialog input as an Integer - android

I have an AlertDialog where the user needs to type a number between 1-24 and I stor that for later use. Now to store the number input as an integer I do this:
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
String test = userInput.getText().toString();
int testNumber;
try {testNumber = Integer.parseInt(test); }
catch (NumberFormatException e) { testNumber = 0;}
Now when testing it seems that whatever number I use as input in the dialog window, it always returns 0, even if it was just a normal number. What can I do that I don't get a NumberFormatException?
EDIT:
After further testing I found that whatever I give as input on my emulator, I always get an empty string.

testNumber = Integer.parseInt(test.trim());
Replace with this, it will be fixed.
.trim() removes extra spaces.

Related

UnitTesting for EditText , testing multiple values

Hi I am trying to test the edit Text placing 2 different values but the second test is failing .reasons unknown...below is my code
TestCase1
public void testvalues1() {
// clearing the edit text
mTextView.clearComposingText();
TouchUtils.tapView(this, mTextView);
// sending input as 7
sendKeys("7");
String userInput1;
String expected = "158269.3778";
String parameterFrom1 = "0.0027";
String parameterTo1 = "61.04676";
// getting the input from the mTextView reference
userInput1 = mTextView.getText().toString();
String resultset = UnitCalculation.Converter(parameterFrom1,userInput1,parameterTo1);
assertEquals(resultset, expected);
}
In the above test case iam sending value 7 and output is as expected
TestCase2
public void testvalues2() {
// clearing the edit text
mTextView.clearComposingText();
TouchUtils.tapView(this, mTextView);
// sending input as 23
sendKeys("23");
String userInput1;
String expected = "150.5011";
String parameterFrom1 = "1.092607";
String parameterTo1 = "7.149502";
// getting the input from the mTextView reference
userInput1 = mTextView.getText().toString();
String resultset1 = UnitCalculation.Converter(parameterFrom1,userInput1,parameterTo1);
System.out.println("printing resilt set "+ resultset1);
assertEquals(resultset1, expected);
}
But the method is returning value 0 instead of 150.5011
Iam using the same methos to calculate, When i give User value hardcoded like this String userInput1="23"; it is working, but when is taking the value from edittext its is not working.
can i send multiple values to edit text on the same testfile??
sendKeys with more than one character is what messed it up. See this reference.
To sum up, sendKeys needs a String which contains space separated keys. Your sendKeys("23")is trying to find a key in the soft keyboard called 23, though there isn't. Try using this:
sendKeys("2 3");
As it will send these two key strokes individually, instead of trying to find a key named 23. That's why sending just a 7 worked, because 7 is the key name for "7".

Getting Int from EditText causes error?

So first of all sorry if this has already been asked and answered before, I couldn't find anything relating to my issue.
So I'm working on a project for college and I need to get int values from EditText widgets. I was told to use parseInt to do this however when running my program, that line of code causes the application to crash. I don't know what I'm doing wrong, I'm still very new to android development, thanks for the help :)
public void Calculate (View view)
{
int MilesTravelled;
int FuelUsed;
int MPG;
/* the two lines below are what cause the application to crash */
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
FuelUsed = (int) (FuelUsed / 4.55);
MPG = MilesTravelled / FuelUsed;
lblMPG.setText(FuelUsed);
}
Do you have this in the onCreate() function?
EditText txtMilesTravelled = (EditText) findViewById(R.id.YourEditText);
But I think you mixed Integer and int. They are not the same:
See this link!
First of all, don't capitalize the first letter of an variables or method names. Following the Java coding conventions, only do that for classes.
What is probably causing your app to crash is you trying to set the text of a label to an integer. The setText method for a TextView needs to take in a string.
So change:
lblMPG.setText(FuelUsed);
to:
lblMPG.setText(String.valueOf(FuelUsed));
Otherwise it might be that it's trying to parse a non-numerical string to an integer.
For exmaple, if the EditText is blank, it will cause your app to crash. To prevent that, try this:
int MilesTravelled = 0, FuelUsed = 0;
try {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(), "Error NFE!", 0).show();
nfe.printStackTrace();
}
This way, it will catch a NumberFormatException error (parsing a string to an integer that can't be represented as an integer, such as "hello"). If it catches the error, it will toast that an error has occurred and your integer variables will remain 0.
Or you could just test if the strings contain only digits using the following regex:
int MilesTravelled = 0, FuelUsed = 0;
if (txtMilesTravelled.getText().toString().matches("[0-9]+")) {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
} else {
// contains characters that are not digits
}
if (txtFuelUsed.getText().toString().matches("[0-9]+")) {
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} else {
// contains characters that are not digits
}
If that's not the problem, then make sure you define your variables properly.
txtMilesTravelled and txtFuelUsed should be EditText:
EditText txtMilesTravelled = (EditText)findViewById(R.id.txtMilesTravelled);
EditText txtFuelUsed = (EditText)findViewById(R.id.txtFuelUsed);
And make sure that your R.id.editText actually exists on your layout and that the IDs are the correct ones.
Last thing, make sure FuelUsed is not 0 before calculating MPG because then you are dividing by 0:
int MPG = 0;
if (FuelUsed != 0) {
MPG = MilesTravelled / FuelUsed;
}
I am assuming that you're entering perfect integers in the EditTexts. It might be a good idea to use the trim function txtMilesTravelled.getText().toString().trim() before using parseInt.
However, I think the major problem is here : lblMPG.setText(FuelUsed);
FuelUsed is an integral value, when you pass an integer to setText(), it looks for a string resource with that integral value. So you should be passing a String to the setText() method.
Use : lblMPG.setText(Integer.toString(FuelUsed));

Determine if content in editText is a "." ONLY

I have written a calculator type app. My mates found that entering single decimal points only into the editText's makes the app crash. Decimal numbers and integers work fine, but I get a number format exception when .'s are entered.
I want to check if a single . has been placed in an editText, in order for me to display a toast telling the user to stop trying to crash the app.
My issue is that a . doesn't have a numerical value...
You can wrap it in a try/catch which should be done anyway when parsing text. So something like
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
This way it will protect against any number format exception and will make the code more reusable later on.
You can treat .1 as 0.1 by the following.
String text = et.getText().toString();
int len = text.length();
// Do noting if edit text just contains a "." without numbers
if(len==0 || (len==1 && text.charAt(0).equals(".")))
return;
if(text.charAt(0).equals(".") && text.length() > 1) {
text = "0" + text;
}
// Do your parsing and calculations

Compare R.id to int

I am building an simple Android app am looking for a way to compare number input to a pre-stored integer. My first though was:
if(R.id.number == 123456){
}
This comparison does not work. I have also tried .equals, with no avail. Does anyone have any thoughts on how to compare the two values?
The R.id.number refers to a View's id (most likely an EditText since you say you are comparing user input). Thus, comparing that to a number would definitely not be what you're looking for. Find the EditText via findViewById(), parse its text into an integer and compare that.
Eg
public void onCreate (Bundle b){
super.onCreate (b);
EditText e = (EditText) findViewById (R.id.number);
int num = 0;
try{
num = Integer.parseInt (e.getText().toString().trim());
}
catch (NumberFormatException e){
}
if (num == 123456){
System.out.println ("Input equal");
}
}

Calling a phone number provided by GooglePlaces in Android

So using google places reference (detailed web-service) i retrieved a "formatted phone number" its in the form of (256) 922-0556. The goal is to call this number. The way I am trying is be using an intent. However, the number above is not a in the format to use Uri parse method. Anyone know a solution to call this number? Is there a different intent or a good way to turn this into Uri data? I have seen the opposite of this done like so:
1234567890 → (123) 456-7890
String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);
But i want to do the reverse of this. any ideas or alternative solutions?
Here is my code:
protected void onPostExecute(Boolean result){
Intent callintent = new Intent(Intent.ACTION_CALL);
callintent.setData(Uri.parse(phoneNum));
try {
startActivity(callintent);
}catch (Exception e) {e.printStackTrace();}
}
Where phoneNum is a formatted phone number string retrieved from GooglePlaces via JSON
To expand on Peotropo's comment: is there a better way to replace values than the following?
phoneNum = phoneNum.replace(" ", ""); // gets rid of the spaces
phoneNum = phoneNum.replace("-", ""); // gets rid of the -
phoneNum = phoneNum.replace("(", ""); // gets rid of the (
phoneNum = phoneNum.replace(")", ""); // gets rid of the )
This is simple string. Use String.replace() method to remove extra chars.
You can also use replaceAll method:
String phoneNumber = "(123)123-456465"
return phoneNumber.replaceAll("[^0-9]", "");
Not tested docs are here:
replaceAll
Java regular expressions
You don't need to do a string replace. You can use the Spannable code below to have your phone automatically recognize the number and call it. It adjusts for parentheses, spaces and dashes.
// call the phone
SpannableString callphone = new SpannableString("Phone: " + phone);
callphone.setSpan(new StyleSpan(Typeface.BOLD), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
callphone.setSpan(new URLSpan("tel:"+phone), 7, 21, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView zphone = (TextView) findViewById(R.id.phone);
zphone.setText(callphone);
zphone.setMovementMethod(LinkMovementMethod.getInstance());
It will display
Phone: (123) 456-7890
Where you see 7,21 in the code above it is saying to start at the 8th character, which is the ( and end at the 21st character which is the last digit in the phone number. Adjust it to display how you want.
Nothing special to do in your view:
<!-- Phone Number Label -->
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"/>

Categories

Resources