0

I have a problem where by a section of my android app works fine on android version 4.1.2 but throws a NullPointerException when the same section is executed on android 4.4.3. My minimum sdk is set to 15 and target sdk is 21. Please find the code below:

try {
    FileInputStream towe = new FileInputStream(path2);
    re = new BufferedReader(new InputStreamReader(towe));
    while ((res = re.readLine()) != null) {
        result.append(res);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        re.close();           //ERROR IS GENERATED AT THIS LINE
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Morning guys, been away for a while. It turned out Exception was being thrown because of file path. I had hard-coded the path for android 4.1.2 but in 4.4.3 that path was different even though device was the same. I ended up using the

android.os.Environment.getExternalStorageDirectory();

method. Now working fine on both. Thanks for the suggestions

NMP263
  • 1
  • 3

1 Answers1

2

This is the correct way to write this, from a number of perspectives:

 try (FileInputStream towe = new FileInputStream(path2);
      Reader re = new BufferedReader(new InputStreamReader(towe))) {
    while ((res = re.readLine()) != null) {
        result.append(res);
    }
 }
  1. Use try-with-resources. It is simpler, and more concise.
  2. Don't catch an exception, and continue as if nothing happened. If you find yourself doing this, you are probably catching the exception in the wrong place.
  3. Printing stacktraces in random places is a bad idea.

If you don't use try-with-resources then you need to test that re is non-null in the finally block to avoid the NPE. It would look like this with the erroneous stacktraces and exception squashing removed.

 try {
    FileInputStream towe = new FileInputStream(path2);
    re = new BufferedReader(new InputStreamReader(towe));
    while ((res = re.readLine()) != null) {
        result.append(res);
    }
 } finally {
     if (re != null) {
        re.close();
     }
 }

And even then, there is a theoretical risk that towe won't be closed. (Hint: Error subclasses.)


NullPointerException on android 4.4.3 but not 4.1.2

What that most likely means is that new FileInputStream(path2); is throwing an exception (probably an IOException of some kind) on one platform and not the other. The clue is most likely in the I/O exception's message.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • Agreed, butn ot helpful for the problem, though. – J. Dow Apr 22 '16 at 13:19
  • Morning guys, been away for a while. It turned out Exception was being thrown because of file path. I hard-coded the path for android 4.1.2 but in 4.4.3 that path was different even though device was the same. I ended using the android.os.Environment.getExternalStorageDirectory(); – NMP263 May 10 '16 at 07:35