android number format exception - android

I get the following exception
java.lang.NumberFormatException: Invalid int: ""
It is happening when you try to store a value into shared preferences whilst nothing has been inserted into the input field. This is because i am parsing the input as an int (as i need to do a subtraction with the figure)
This isn't much of a problem as the app will work however just incase someone using the app wants to be wierd and try and press the save button without entering any data I dont want it to insert.
I have tried the following:
else if (obj ==null || obj.currentWeight.contains("")||obj.targetWeight.contains("")){
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("No Data Stored");
builder.setMessage("Please insert your target weight and your current weight and click Store Weight")
.setPositiveButton("OK", null).show();
From what i could make out if i kept the above statement as
else if (obj ==null){
then if a null is inserted the dialog would open and display a message.
i get the number format exception.
any help would be appreciated

Generally speaking, exception processing is a good approach for this kind of undesired behavior :
if( obj != null && obj.getTargetWeight() != null ) {
try {
int i = Integer.parseInt( obj.getTargetWeight() );
//do something if target weight is a number
} catch( NumberFormatException ex ) {
//do something if target weight was not a number.
}
}
---edited to precise exception type

Related

GetText compare

So i have a EditText field, which i want to, check if the age is above and under my limits.
if (Integer.parseInt(age.getText().toString()) < 18 && Integer.parseInt(age.getText().toString()) >= 0)
But also, i want to simply check if the field is empty, for what i used.
else if (age.getText().toString().isEmpty())
Unluckly this one is not working, i think it sort of get in to conflict with the first one or something, because i tried with just one condition of both, and it works..
I also tried to store in String variable the method to check isEmpty(), and also in int one, to do the age comparation, but it still not working.
Thanks in advance.
The code should be:
if (age.getText().toString().trim().isEmpty()){
//The EditText field is empty
}else{
try{
if (Integer.parseInt(age.getText().toString().trim()) < 18 && Integer.parseInt(age.getText().toString().trim()) >= 0){
//Your code here
}else{
//Input value is over 18 or under 0
}
}catch(Exception ex){
//There was an error parsing the input (if your user writes letters, parseInt fails)
}
}

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

EditText Validation setError not working, getting crashed

I'm doing the check for my two EditText field editNumber1 and editNumber2.
I'm trying to display if the check perform fails.
I'm not able to display the error and the application crashes.
here is the sample code can any one suggest?
if ((editNumber1.getText().length() == 0) || (editNumber1.getText().toString() == " ") ||
(editNumber2.getText().length() == 0) || (editNumber2.getText().toString() == " "))
{
editNumber1.setFocusableInTouchMode(true);
editNumber1.requestFocus();
editNumber1.setError("Some inputs are empty");
}
Firs of all use this good utilities StringUtils.isNotBlank( string_to_compare );
this method return false if the string_to_compare is:
null,
empty (""),
blank (" ")
then try to use a break point in the lines below to see when the crash occurs
editNumber1.setFocusableInTouchMode(true);
editNumber1.requestFocus();
editNumber1.setError("Some inputs are empty");

android apps using if else statement with multiple condition

Hye, I have a problem and a bit confuses to solve it… I need to create a checklist for user to answer in my android apps..it contain several questions…for example, I have 5 questions and user need to answer by choosing the options on radiobutton…So basically this checklist is to check if the user is allowed to drive a car or not..
1) Are you under influence of drugs? //RG1, rbyes1, rbno1
O Yes O No
2) Do you have driving license? //RG2, rbyes2, rbno2
O Yes O No
3) Do you have a car? //RG3, rbyes3, rbno3
O YES O No
4) Are you drunk? //RG4, rbyes4, rbno4
O Yes O No
5) Are you colour blind? //RG5, rbyes5, rbno5
O Yes O No
User need to answer
1) No
2) Yes
3) Yes
4) No
5) No
To make the user eligible to drive a car..
If user answer the opposite, system should display the reason for every opposite answer..
This is my sample code
If(RG1. getCheckedRadioButtonId() == R.id.rbno1 &&
RG2. getCheckedRadioButtonId() == R.id.rbyes2 &&
RG3. getCheckedRadioButtonId() == R.id.rbyes3 &&
RG4. getCheckedRadioButtonId() == R.id.rbno4 &&
RG5. getCheckedRadioButtonId() == R.id.rbno5)
{
Toast.makeText(getApplicationContext(),”Congratz, you can drive”, Toast.LENGTH_LONG).show();
}
Above code is user answers for the eligible one..what if the user answer like this
1) No
2) No
3) Yes
4) Yes
5) No
So, system should display
{
Toast.makeText(getApplicationContext(),”Sorry, you are not allow to drive because you have\n“+
“2) No driving license\n” +
“4) influenced of alcohol\n”, Toast.LENGTH_LONG).show();
}
This is a piece of my idea for what I can do..Do I need to create every possibilities???.. because for the actual one, I got more than 10 questions… So, that’s means there will have many condition.. and I also confuse how to write it in code because of too many condition..hopefully you guys understand what I means and can help me…thank you..!
You do not need to check for every possibility. You check every answer only once and keep track of the error messages, e.g.:
boolean canDrive = true;
ArrayList<String> errorMessages = new ArrayList<String>();
if(RG1.getCheckedRadioButtonId() == R.id.rbno1) {
canDrive = canDrive && true;
} else {
canDrive = false;
errorMessages.add("Influenced of drugs");
}
if(RG2.getCheckedRadioButtonId() == R.id.rbyes2) {
canDrive = canDrive && true;
} else {
canDrive = false;
errorMessages.add("No driving license");
}
// Check the rest of your answers
At the end of your conditions you will have the variable canDrive reflects the result of the user answers and you will have all the error messages in errorMessages list which you can loop through and display appropriately.
Try to make your code more generic, consider using Array of your CheckedRadioButtons and you can store the error message for each question using checkBox.setTag()
Solution 1:
In my opinion you have to create on Database for storing the result.
When you have to require print the error message that time you have to fire on simple select query with result yes.
then print your message
Solution 2:
You have to create arrayList and store result value if yes.
Then you have to find length of arrayList and put your condition and put message

Else if loop doesn't validate variable from statement

I am having a problem while looping through one of my loop constructions.
I get Question instances out of my database and one of the fields of the instance is Attempts. I pulled my database from my device and inspected it and all fields of the column attempts are filled with ints greater than 0.
int initialAttempts = 0;
initialAttempts = c.getInt(6);
q.setAttempts(initialAttempts);
and in my custom array adapter:
if (mView != null) {
int attempts = getItem(position).getAttempts();
int correctAnswer = getItem(position).getAnswerCorrect();
triangle.setVisibility(View.INVISIBLE);
if(correctAnswer == 1) {
triangle.setVisibility(View.VISIBLE);
}
else if (correctAnswer != 1 && attempts > 0) {
triangle.setVisibility(View.VISIBLE);
triangle.setImageResource(R.drawable.trianglered);
}
So the problem is it never shows trianglered. If I drop the && attempts > 0, it does show the trianglered, so I assume the error is in there. The strange thing is if I initialize attempts as 1 before the getItem(position).getAttempts, it still shows no trianglereds.
Any ideas where this goes wrong?
getItem(position).getAttempts() method returns 0. There are no other variants. Why it returns 0 is the question to you. Prefer debugging instead of asking such questions.
PS. No need to check for correctAnswer != 1 in else if statement. The opposite statement has already been checked in if and it was false.

Categories

Resources