Android app crashes when no value is in edit text - android

I am making a unit converter, but if I do not enter any value into edit text and press the calculate button the app crashes with error Invalid float: "". Also, I want to forbid zeroes from being entered before numbers (eg. 0300). How do I accomplish this?
//handle calculate
calcButton=(Button)findViewById(R.id.calcButton);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Spinner spinner = (Spinner) findViewById(R.id.unit_spinner);
String spinnerText = spinner.getSelectedItem().toString();
EditText unit_edit = (EditText) findViewById(R.id.unit_edit);
amount = Float.valueOf(unit_edit.getText().toString());
if (unit_edit.getText().toString().equals(null)) {
Toast.makeText(getApplicationContext(), "Insert Value To Convert",
Toast.LENGTH_LONG).show();
} else {
switch (spinnerText) {
case "Kilograms":
kilograms = amount;
grams = amount * 1000;
ListView();
break;
case "Grams":
grams = amount;
kilograms = amount / 1000;
ListView();
break;
}
}
}
});
}

You are probably getting an NumberFormatException thrown since the EditText fields text is "" and "" is not a valid float value, the exception is thrown at the following line:
amount = Float.valueOf(unit_edit.getText().toString());
What you'll need to do is add some validation and checking before trying to get the float value of a String.
Check the methods documentation for more details http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf(java.lang.String)

This might be useful for your EditText to limit input to numbers only.
<EditText
android:id="#+id/unit_edit"
android:inputType="number"
/>
You can also limit the digits, type of number such as decimal
<EditText
android:id="#+id/unit_edit"
android:digits="0123456789."
android:inputType="numberDecimal"
/>

You can't parse an empty value to float. You should first test if it's empty, and then do what you want, something like this:
String text = unit_edit.getText().toString();
if(!text.isEmpty()){ // Test if the text is empty
if(text.matches("[0-9]+")){ // Test if it only contains numbers, using REGEX
amount = Float.valueOf(text); // Only then parse to float.
// Switch and rest of the stuff
} else {
Toast.makeText(getApplicationContext(), "Use only numbers from 0 to 9.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "The field is empty",
Toast.LENGTH_LONG).show();
}
The comments explain what's going on. About the leading 0 in some numbers, using "valueOf" will remove it already, and 0300 will be parsed as 300, so there's nothing to worry about.If you still want something related to it, let me know and i'll edit my answer.

Related

How to Validate Phone Number format

i am about to create a validation for phone number format..The format is 10 digit including the plus sign eg:+0133999504. Even though I have declare the pattern which is I try to disallow the "-" symbol or any other characters, but the validation is not working. Any other Idea or solution?
1st I declared the string regex:
String PhoneNo;
String PhoneNo_PATTERN ="[\\+]\\d{3}\\d{7}";
2nd I make a if..else statement:
{
Pattern pattern = Pattern.compile(PhoneNo_PATTERN);
Matcher matcher = pattern.matcher(PhoneNo);
if (!matcher.matches())
{
inputemergencyContactNo.setError("Please enter Emergency Contact No");
}
else{
Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
}
Why not remove all non-digits and then count the digits left and put the plus back in later? This allows users the freedom to fill out their phone number anyway they want...
String PhoneNo = "+123-456 7890";
String Regex = "[^\\d]";
String PhoneDigits = PhoneNo.replaceAll(Regex, "");
if (PhoneDigits.length()!=10)
{
// error message
}
else
{
PhoneNo = "+";
PhoneNo = PhoneNo.concat(PhoneDigits); // adding the plus sign
// validation successful
}
If your app is intended for international use replace
if (!PhoneDigits.length()!=10)
with
if(PhoneDigits.length() < 6 || PhoneDigits.length() > 13)
as Fatti Khan suggested.
To apply this in the code you posted at Android EditText Validation and Regex first include this method in your public class or the class containing onClick():
public boolean validateNumber(String S) {
String Regex = "[^\\d]";
String PhoneDigits = S.replaceAll(Regex, "");
return (PhoneDigits.length()!=10);
}
And include this method in the CreateNewRider class:
protected String tidyNumber(String S) {
String Regex = "[^\\d]";
String PhoneDigits = S.replaceAll(Regex, "");
String Plus = "+";
return Plus.concat(PhoneDigits);
}
This is where the validation happens...
#Override
public void onClick(View view) {
Boolean b = false;
if(inputfullname.getText().toString().equals("")) b = true;
else if(... // do this for all fields
else if(inputmobileNo.getText().toString().equals("")) b=true;
else if(inputemergencyContactNo.getText().toString().equals("")) b=true;
else {
if(validateNumber( inputmobileNo.getText().toString() )
Toast.makeText(RiderProfile.this, "Invalid mobile number", Toast.LENGTH_SHORT).show();
else if(validateNumber( inputemergencyContactNo.getText().toString() )
Toast.makeText(RiderProfile.this, "Invalid emergency contact number", Toast.LENGTH_SHORT).show();
else {
// Validation succesful
new CreateNewRider().execute();
}
}
if(b) Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
}
And then use tidyNumber() in the CreateNewRider class:
protected String doInBackground(String... args) {
String fullname= inputfullname.getText().toString();
String IC= inputIC.getText().toString();
String mobileNo= tidyNumber( inputmobileNo.getText().toString() );
String emergencyContactName= inputemergencyContactName.getText().toString() );
String emergencyContactNo= tidyNumber( inputemergencyContactNo.getText().toString() );
...
Given the rules you specified:
upto length 13 and including character + infront.
(and also incorporating the min length of 10 in your code)
You're going to want a regex that looks like this:
^\+[0-9]{10,13}$
With the min and max lengths encoded in the regex, you can drop those conditions from your if() block.
Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.
[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:
^[+][0-9]{10,13}$
[EDIT 2] OP now adds that the + sign should be optional. In this case, the regex needs a question mark after the +, so the example above would now look like this:
^[+]?[0-9]{10,13}$
For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number . Also we can not check like mobile number must starts with 9 or 8 or anything..
For mobile number I used this this Function
private boolean isValidMobile(String phone2)
{
boolean check;
if(phone2.length() < 6 || phone2.length() > 13)
{
check = false;
txtPhone.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
^[\\+]\\d{3}\\d{7}$
Use anchors to limit the match.
^ => start of match
$=> end of match
To validate India's mobile number.
Your edit text input
edt_mobile.text.toString().trim()
Number validation method
fun isValidMobile(phone: String): Boolean {
return phone.matches(Constants.REGEX_MOBILE.toRegex()) && phone.trim().length == 10
}
Regression expression
const val REGEX_MOBILE = "^[6-9]{1}[0-9]{9}\$"

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

change text color based on value of text

I am trying to figure out how to change the color of TextView based on the value of the text.
TextView has been sent from another activity I have that part working fine. What I want is a way to change the color of the text based on what is in the TextView. So if previous Activity sends a value like "11 Mbps" as TextView then I would like that text color to be yellow, "38 Mbps" green, and 1 Mbps red. I'm using eclipse if that helps at all.
This is how I'm sending the TextView to another activity. "showmsg" is just username sent to another page.
buttonBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
final TextView username =(TextView)findViewById(R.id.showmsg);
String uname = username.getText().toString();
final TextView wifistrength =(TextView)findViewById(R.id.Speed);
String data = wifistrength.getText().toString();
startActivity(new Intent(CheckWiFiActivity.this,DashboardActivity.class).putExtra("wifi",(CharSequence)data).putExtra("usr",(CharSequence)uname));
}
});
And this is how I receive it in the other activity
Intent i = getIntent();
if (i.getCharSequenceExtra("wifi") != null) {
final TextView setmsg2 = (TextView)findViewById(R.id.Speed);
setmsg2.setText(in.getCharSequenceExtra("wifi"));
}
This all works fine but I don't have a clue how to change the color of TextView based of the value of the text. Any help would be really appreciated.
You obviously want to set the color according to the number in the String you received from the previous Activity. So you need to parse it out of the String, save it to an int and then according to what the number is, set the color of your TextView.
String s = in.getCharSequenceExtra("wifi");
// the next line parses the number out of the string
int speed = Integer.parseInt(s.replaceAll("[\\D]", ""));
setmsg2.setText(s);
// set the thresholds to your liking
if (speed <= 1) {
setmsg2.setTextColor(Color.RED);
} else if (speed <= 11) {
setmsg2.setTextColor(Color.YELLOW);
else {
setmsg2.setTextColor(Color.GREEN);
}
Please notice that this is an untested code, it might contain some mistakes.
The way to parse it comes from here.
First, get all of the non-numeric characters out of your String and convert it to an integer. Then use a switch on the new value and set the color accordingly
String color = "blue"; // this could be null or any other value but I don't like initializing to null if I don't have to
int speed = i.getCharSequenceExtra("wifi").replaceAll("[^0-9]", ""); // remove all non-digits here
switch (speed)
{
case (11):
color = "yellow";
break;
case (38):
color = "green";
break;
case(1):
color = "red";
break;
}
setmsg2.setTextColor(Color.parseColor(color);
Here is a little site with some handy information
Color Docs

Check value in text view

I have a if condition for check value in textview but it still happen only else condition
what I did wrong, why it doesn't have if condition even if I have set lang=space
private void setLangTitle() {
lang.setText(" ");
db.open();
Cursor cc = db.getLangAct();
cc.moveToFirst();
int index = cc.getColumnIndex(DBAdapter.KEY_LANG);
while (cc.isAfterLast() == false) {
if(lang.equals(" ")){
lang.append("p"+cc.getString(index));
cc.moveToNext();
}
else {
lang.append("/" + cc.getString(index));
cc.moveToNext();
}
}
db.close();
}
You're currently checking if lang is equal to a space character. If lang is a TextView, than it will not be equal to the space character because it is a TextView object, not a string. You probably want to test if the text being displayed on lang is equal to the space character, which would be something along the lines of:
if (lang.getText().toString().equals(" ")) {
...
}
I assume that lang is your TextView object? Then you should use lang.getText().toString()
you should use
if(lang.getText()equals(" ")){
...
}
You were not comparing texts, you were comparing objects. And, of course, a TextView doesn't (shouldn't) compare equal to a String.

Categories

Resources