0

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

Tuffy G
  • 1,521
  • 8
  • 31
  • 42

1 Answers1

2

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

Snicolas
  • 37,840
  • 15
  • 114
  • 173