Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crashing due to Integer.parseInt

I'm trying to import text from a text file which has been generated in another Activity. The generated text file is made up of a String ArrayList which only contains numbers and the other random text generated by Android. When I import the text from the file I'm using a BufferedReader and readLine() to get each new number into an Integer ArrayList. I'm removing any non-numerical values from the text file and the numbers that are generated in the other Activity are split up by an "\n".

The problem that I'm facing is that Android crashes when it loads the Activity. I've narrowed the cause down to Integer.parseInt().

My code is below:

ArrayList<Integer> lines = new ArrayList<Integer>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        File file = new File(getFilesDir(), "test_file.txt");

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while (br.readLine() != null) {
                String text = (br.readLine()).replaceAll("[^0-9]+","").trim();
                Integer number = Integer.parseInt(text);
                lines.add(number);
            }
        } catch (IOException e) {

        }

        TextView tv = (TextView) findViewById(R.id.helptext);

        int max = 0, min = 100;
        double total = 0;
        for (int i = 0; i < lines.size(); i++) {
            int number = lines.get(i);
            max = Math.max(max, number);
            min = Math.min(min, number);
            total += number;
        }

        tv.setText("max = " + max + " min = " + min + " total = "
                + total);
like image 680
BGM Avatar asked Sep 03 '11 09:09

BGM


People also ask

What happens if integer parseInt fails?

We have used the parseInt method of the Integer class before. The method throws a NumberFormatException if the string it has been given cannot be parsed into an integer. The above program throws an error if the user input is not a valid number. The exception will cause the program execution to stop.

What can I use instead of integer parseInt?

If you're concerned with converting a String to an Integer object, use the valueOf() method of the Integer class instead of the parseInt() method.

What does parseInt return if failed?

If the first character cannot be converted to a number with the radix in use, parseInt returns NaN .

What is integer parseInt?

The method parseInt() belongs to the integer class which is under java. lang package . It is used to parse the string value as a decimal value that is signed. It is used in java for typed conversion for converting a string value to an integer by using the method parseInt().


2 Answers

Problems:

  • When you do replaceAll("[^0-9]+","") you can end up with an empty string causing Integer.parseInt to throw an NumberFormatException.

  • You are skipping every other line (your while loop condition consumes the first line, the third line and so on...)

    while (br.readLine() != null) // consumes one line
    

Try something like this:

BufferedReader br = new BufferedReader(new FileReader(file));
String input;
while ((input = br.readLine()) != null) {
    String text = input.replaceAll("[^0-9]+","");
    if (!text.isEmpty())
        lines.add(Integer.parseInt(text));
}
like image 186
dacwe Avatar answered Oct 20 '22 19:10

dacwe


All the above answers are true but they won't help you if, for some reasons data coming to you isn't an Integer. eg- Server by mistake sent you user name instead of userId (should be an Integer).

This might happen so we must always place in checks to prevent it. Otherwise, our app will crash and it won't be a pleasant user experience. So, while converting String to Integer, always use a try-catch block to prevent app crashes. I use following code to prevent app crash due to Integer parsing -

try {
     Log.d(TAG, Integer.parseInt(string));
    } catch (NumberFormatException e) {
      Log.w(TAG, "Key entered isn't Integer");
    }
like image 3
Rohan Kandwal Avatar answered Oct 20 '22 18:10

Rohan Kandwal