android number format exception

情到浓时终转凉″ 提交于 2019-12-02 16:02:14

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/10104267/android-number-format-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!