0

I am new to this, but I am writing an app and I keep getting this error cause the app to crash on start.

java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedWriter.close()' on a null object reference 

The code causing it is in the class below, there will be a HERE comment next to the line with the issue.

public class FileOptions extends Activity{ public void createFile(String title, String storeValue){ BufferedWriter bufferWriter = null; try { FileOutputStream fileOutputStream = openFileOutput(title, Context.MODE_PRIVATE); bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream)); String content = storeValue; bufferWriter.write(content); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { //Cannot be removed e.printStackTrace(); } finally { try { /**HERE*/ bufferWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } //More unimportant stuff } 

This is the code where I am calling the method from.

public class MainActivity extends ActionBarActivity { Context context = this; boolean debug = true; FileOptions file = new FileOptions(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE) .getBoolean("isfirstrun", true); if(isFirstRun) { file.createFile("userInfo", ""); getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isfirstrun", false).commit(); } if(file.readFile("userInfo") != "") { if(debug){alerter(file.readFile("userInfo"));alerter("true");} switchToHome(); }else{ if(debug){alerter("false");} } } } 

Here is the stack trace.

08-27 22:44:35.830 13089-13089/? I/libpersona﹕ KNOX_SDCARD checking this for 10247 08-27 22:44:35.830 13089-13089/? I/libpersona﹕ KNOX_SDCARD not a persona 08-27 22:44:35.830 13089-13089/? E/Zygote﹕ MountEmulatedStorage() 08-27 22:44:35.830 13089-13089/? E/Zygote﹕ v2 08-27 22:44:35.830 13089-13089/? I/SELinux﹕ Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_SM-N910V_5.0.1 ver=27 08-27 22:44:35.830 13089-13089/? I/SELinux﹕ Function: selinux_compare_spd_ram , priority [1] , priority version is VE=SEPF_SM-N910V_5.0.1_0027 08-27 22:44:35.830 13089-13089/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL 08-27 22:44:35.830 13089-13089/? I/art﹕ Late-enabling -Xcheck:jni 08-27 22:44:35.870 13089-13089/? D/TimaKeyStoreProvider﹕ TimaSignature is unavailable 08-27 22:44:35.870 13089-13089/? D/ActivityThread﹕ Added TimaKeyStore provider 08-27 22:44:35.920 13089-13089/? D/ResourcesManager﹕ creating new AssetManager and set to /data/app/preventioninnovations.preventapp-2/base.apk 08-27 22:44:36.050 13089-13089/? D/AndroidRuntime﹕ Shutting down VM 08-27 22:44:36.050 13089-13089/? E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: preventioninnovations.preventapp, PID: 13089 java.lang.RuntimeException: Unable to start activity ComponentInfo{preventioninnovations.preventapp/preventioninnovations.preventapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedWriter.close()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2712) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2777) at android.app.ActivityThread.access$900(ActivityThread.java:179) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5972) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedWriter.close()' on a null object reference at preventioninnovations.preventapp.FileOptions.createFile(FileOptions.java:37) at preventioninnovations.preventapp.MainActivity.onCreate(MainActivity.java:38) at android.app.Activity.performCreate(Activity.java:6289) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2777)             at android.app.ActivityThread.access$900(ActivityThread.java:179)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:145)             at android.app.ActivityThread.main(ActivityThread.java:5972)             at java.lang.reflect.Method.invoke(Native Method)             at java.lang.reflect.Method.invoke(Method.java:372) 

Thanks for any help.

5
  • 3
    It would be helpful seeing your stacktrace Commented Aug 28, 2015 at 2:57
  • possible duplicate of What is a Null Pointer Exception, and how do I fix it? Commented Aug 28, 2015 at 3:12
  • before calling bufferWriter.close() check whether it is not null. if it is null, you can not call .close() which returns NPE. Commented Aug 28, 2015 at 3:12
  • It may be similar but I feel that with the differences in the code it is OK to ask a new question. Commented Aug 28, 2015 at 3:13
  • Well the same code works if I don't separate it out into a class, so I guess that is what I am going with. I realize that you can check if it is null but then it will not create the file needed(I think?) Commented Aug 28, 2015 at 4:06

4 Answers 4

5

This happens when your openFileOutput() method throws an exception.

Since an exception was thrown bufferWriter was not initialized to a valid object.

And the exception caused the execution to skip the rest of try block go to catch block and then finally block.

So, when it reached the finally block, bufferWriter was null.

finally { try { if (bufferWriter != null) bufferWriter.close(); } catch (IOException e) { e.printStackTrace(); } } 

To fix, check for null before calling close in bufferWriter.

Or still better use try with resources.

try(BufferedWriter = new BufferedWriter( new OutputStreamWriter( openFileOutput(title, Context.MODE_PRIVATE)))) {} 
Sign up to request clarification or add additional context in comments.

Comments

1
finally { if(bufferWriter!=null){ bufferWriter.close();/**HERE*/ } } 

By the looks your bufferWriter is null. So maybe the file you are giving it is not working? This stop a NPE if bufferwriter is null.

Comments

1

Java 7 gives you a much cleaner interface for try-catch blocks.

You can read more on the alternative methods from this SO answer.

public void createFile(String title, String storeValue){ try ( FileOutputStream fileOutputStream = openFileOutput(title, Context.MODE_PRIVATE); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream)) ) { String content = storeValue; bufferWriter.write(content); } catch (FileNotFoundException e) { e.printStackTrace(); } } 

Comments

0

Found the issue. I needed to pass the context of the class I was calling from to the method for it to work.

I had:file.createFile("userInfo", ""); and I needed:file.createFile("userInfo", "", this);

then in the method I had:

public void createFile(String title, String storeValue){ BufferedWriter bufferWriter = null; try { FileOutputStream fileOutputStream = openFileOutput(title, context.MODE_PRIVATE); bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream)); 

Where I needed:

public void createFile(String title, String storeValue, /** ADDED */Context context){ BufferedWriter bufferWriter = null; try { FileOutputStream fileOutputStream = /** CHANGE IS HERE */ context.openFileOutput(title, context.MODE_PRIVATE); bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.