Converting a String to int. Set the int to 0 if String is null

前端 未结 12 2123
孤街浪徒
孤街浪徒 2021-01-17 10:09

I have a function which saves Android data in sqlite but I have to convert the String data to an Integer.

Whenever the S

相关标签:
12条回答
  • 2021-01-17 10:24

    Your function should work fine only when the param is an empty string instead of null If the param is empty string ,Integer.parseInt would throw a NumberFormatException instead of return 0

    0 讨论(0)
  • 2021-01-17 10:26

    Instead of writing your own function use the inbuild construction of try-catch. Your problem is, that jsonarray or jsonarray.getJSONObject(i) or the value itself is a null and you call a method on null reference. Try the following:

    int block_id = 0;        //this set's the block_id to 0 as a default.
    try {
        block_id =  Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));    //this will set block_id to the String value, but if it's not convertable, will leave it 0.
    } catch (Exception e) {};
    

    In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.

    try{
        //some code
    } catch (NumberFormatException e1) {
        e.printStackTrace()     //very important - handles the Exception but prints the information!
    } catch (NullPointerException e2) {
        e.printStackTrace();
    }
    

    or using the fact, that they all extend Exception:

    try {
        //somecode
    } catch (Exception e) {
        e.printStackTrace;
    };
    

    or since Java 7:

    try {
        //somecode
    } catch (NullPointerException | NumberFormatException e) {
        e.printStackTrace;
    };
    

    Note

    As I believe, that you'll read the answer carefully, please have in mind, that on StackOverflow we require the Minimal, Complete, and Verifiable example which include the StackTrace of your exception. In your case it probably starts with the following:

    Exception in thread "main" java.lang.NullPointerException
    

    Then, debugging is much easier. Without it, it's just guessing.

    Edit: According to the accepted answer

    The accepted answer is good and will work as long, as the value stored with key: block_id will be numeric. In case it's not numeric, your application will crash.

    Instead of:

    JSONObject jObj = jsonarray.getJSONObject(i);
    int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
    

    One should use:

    int block_id;
    try{
        JSONObject jObj = jsonarray.getJSONObject(i);
        block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
    } catch (JSONException | NullPointerException e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2021-01-17 10:30

    You can use following method,

    String id = jsonarray.getJSONObject(i).getString("block_id")
    int blockId = getBlockId(id);
    
    @NonNull
    private Integer getBlockId(String id) {
        Integer blockId= 0;
        try {
            blockId= Integer.parseInt(id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return blockId;
    }
    
    0 讨论(0)
  • 2021-01-17 10:31

    You can check for NumberFormatException. Integer.parseInt() will throw NumberFormatException for cases:

    • String is null
    • String is empty ("")
    • String cannot be converted to int for any other reason (say String is "aff" or "1.25")

    Basically, it will handle all possible non-integer cases.

    Code Example:

    private static int convertStringToInt(String str){
        int x = 0;
        try{
            x = Integer.parseInt(str);
        }catch(NumberFormatException ex){
            //TODO: LOG or HANDLE
        }
        return x;
    }
    
    0 讨论(0)
  • 2021-01-17 10:31

    Notice.. you could also write it like that

     public static Integer convertToInt(String str) {
        int n=0;
        if(str != null && str.length()>0) {
            n = Integer.parseInt(str);
        }
        return n;
    }
    

    but the try/catch method is way more effective and simple and will not cause a system exit if a letter get inside the String (just worth mentioning)

    also, it is important to notice that writing the same equation like that:

    if(str != null & str.length()>0) {}
    

    or like that:

    if(str.length()>0 && str != null) {}
    

    can cause the operation to fail because it will try to count the String even if it is null

    Hope I responded to all your questions

    0 讨论(0)
  • 2021-01-17 10:36

    Try this

     int block_id = (jsonarray.getJSONObject(i).has(block_id)) ? jsonarray.getJSONObject(i).getInt("block_id") : 0;
    
    0 讨论(0)
提交回复
热议问题