Search code examples
javaandroidparseintnumberformatexception

Why am I getting a NumberFormatException trying to parse an integer from string in Android?


I am looking for an update function for a custom ROM based tool. I used this code http://www.androidsnippets.com/check-for-updates-once-a-day as a base and soon realized that I couldn't use Dropbox for deployment with that code. So I modified the code to download a version.txt file from dropbox. The file contains a single number (the latest Version Code, in this case 11). I need to read that line and parse the string as an integer to compare with the current versionCode and trigger a download if an update exists. All the code works, except for parsing the int from the txt file.

Heres my code:

    private Thread checkUpdate = new Thread() {
public void run() {
    try {

        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(sdcard,"BPversion.txt");
        StringBuilder text = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            text.append(line);

        int curVersion = getPackageManager().getPackageInfo("com.JB15613.BPcolorTool", 0).versionCode;
        System.out.println(line);
        int newVersion = 0;
        System.out.println(line);

        try {
            newVersion = Integer.parseInt(line);
            System.out.println(line);
        } catch(NumberFormatException nfe) {
            System.out.println("Exception " + nfe);
        }

        if (newVersion > curVersion) {
            mHandler.post(showUpdate);
        }    
        }
    } catch (Exception e) {
        Log.d("ANDRO_ASYNC", "Caught exception");

    }
}

And I get this exception:

    Exception java.lang.NumberFormatException: Invalid int: "11"

When I apply breakpoints and run the debugger, it crashes at the parseInt line.

11 looks like a valid int to me!

Any help is greatly appreciated!


Solution

  • line ends CRLF ,so , need call function trim() in String ..

    int newVersion = Integer.parseInt(line.trim());