Crashing due to Integer.parseInt
Asked Answered
M

4

10

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);
Mendie answered 3/9, 2011 at 9:2 Comment(0)
A
10

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));
}
Apollonius answered 3/9, 2011 at 9:7 Comment(3)
IT WORKS!!!!!! I had to change text.isEmpty() to text.length() == 0 cause I'm using an older Android API but IT WORKS! THANK YOU SO SO MUCH DACWE!Mendie
@Arjan - sorry about that, I did read through the help about replying in comments but accidentally left out the "@" symbol. Also, I'm so sorry about the tee, I really didn't expect it to cause so much trouble. I had spent so long trying to fix the issue and was so happy when dacwe solved it that I couldn't thank him enough. I assure you it won't happen again. BTW, I have to say that stackoverflow is one of the best, if not the best, sites for code solutions on the internet. If you're one of the guys who helped set it up, thank you so much!!Mendie
@BGM, the tee for dacwe is not a problem, if you read this. Final note, <nitpicking-mode>Stack Overflow likes a space in its name ;-)</nitpicking-mode>. All that said: let's clean up; I am deleting my comments—welcome to Stack Exchange!Endocrinology
O
3

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");
    }
Oread answered 21/8, 2015 at 5:46 Comment(0)
R
0

Ensure text is only numbers in a string, it's likely not. Also you may want to try:

Integer number = Integer.valueOf(text);

instead of:

Integer number = Integer.parseInt(text);

See:

parseInt() returns primitive integer type (int), whereby valueOf returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.

Edit: After your comments below, I'd log text every time in the loop, chances are when it throws the error the log will show the text variable is empty.

Refectory answered 3/9, 2011 at 9:13 Comment(4)
Unfortunately the app is still crashing after trying your code. The way I'm generating my arraylist for the file in the other activity is:Mendie
codeString filename = "test_file.txt"; FileOutputStream fos; try { fos = openFileOutput(filename, Context.MODE_PRIVATE); ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject(arrayList); out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }code ........codearrayList.add(Integer.toString(val[0]) + "\n");codeMendie
** I've checked the codetextcode by printing it out under the textView and there is only numbers in the string after using the replaceAll("[^0-9]*","") function.Mendie
Well either your text variable contains a space perhaps, or is returning empty in the loop.Refectory
T
-1

If you will give numbers as string like "1234" it will not give any exception or error. But you will give any character or special character, then parse() function will throw exception. So please check carefully there must be some character is passing so it is throwing exception and getting crashed

Tuberculosis answered 3/9, 2011 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.