开发者

unable to parse "" as integer[FC]

I have this code to control if a EditTextPreference is null or not:

    case R.id.prochain_vidange:
                settings = PreferenceManager.getDefaultSharedPreferenc开发者_开发问答es(getBaseContext());
                String choix_huile = settings.getString("listPref_huile_moteur", "0");
                km = settings.getString("km", "");
                Log.d("TAG",km);
               int x= Integer.valueOf(km);
               if (km != "")
{
               if (Integer.valueOf(choix_huile) == 0) {
    ............

The problem is in this line:

int x= Integer.valueOf(km);

What could be the problem ? Thanks.


If you give Integer.valueOf(String s) a string that is not a valid number, it throws a NumberFormatException. Change the default value to 0:

km = settings.getString("km", "0");

Alternatively, you can catch the exception, and set x to 0:

km = settings.getString("km", "");
int x;
try {
    x = Integer.valueOf(km);
} catch(NumberFormatException e) {
    x = 0;
}


Integer.valueOf trys to make a new Integer with .parseInteger(String s), "" cant be parsed to a valid number so you get a NumberFormatException

You can catch it with a try catch block or you can simply dont try to make a Integer with the String "".

before:

int x= Integer.valueOf(km);
if (km != "") {

after:

if (km != "") {
int x= Integer.valueOf(km);


Integer.valueOf(km) can throw an exception if the the km string is not able to be parsed as an integer.

However, wrapping it in a try { } catch() block is not an approach I would recommend.

The whole purpose of having a default value on the getString() method in SharedPreferences is that there can be a default value to fall back on if the preference doesn't exist. So the better way to solve this is to modify your settings.getString(...) call to be like this:

 km = settings.getString("km", "0");

Then your subsequent call to Integer.valueOf(km) will not have a blank to fail upon.

Is the input string coming from a blank text field where the user can enter any value? If so, it's at that point that you can validate the value that the user entered. By validating the input early on, you won't need to scatter the checking/validating mechanism to other areas of your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜