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

前端 未结 12 2126
孤街浪徒
孤街浪徒 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:43

    int block_id_0 = jObj.optInt("block_id"); 
    

    The ternary condition and multiple code can simply be replaced with optInt function in a single line, which simply

    1.) return the default value or 0 if no value is there (depends upon the variant you are using).

    2.) Try to convert the value, if the value is available as string

    3.) Simply No null or NumberFormat exceptions at all in case of missing key or value

    Android docs

    int optInt (String name)

    int optInt (String name, int fallback)

    Maven-Central

    int optInt(String key, int defaultValue)

    To get a specified default value if no value available

    Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

    jObj.optInt("block_id",defaultvalue);
    

    or

    To get a default value as 0 if no value available

    Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.

    jObj.optInt("block_id");
    

    e.g

    int block_id = jObj.optInt("block_id",5); 
    

    block_id will be 5 if no key/value available

    int block_id_0 = jObj.optInt("block_id"); 
    

    block_id_0 will be 0 if no key/value available

    There are other variant of this function available for other datatypes as well , try the docs link above.

提交回复
热议问题