I published an app where I need to copy a few hunderd kb size ogg file onto the sdcard of the user. Soon I got an error report. As far as I am concerned the problem might be because the path is not suitable on that specific phone:
String path = "/sdcard/file.ogg";
File file = new File(Environment.getExternalStorageDirectory(), "file.ogg" );
if (!file.exists()) {
InputStream in = getResources().openRawResource(R.raw.file);
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So the report is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.caodeveloping.androgangnam/com.caodeveloping.androgangnam.Main}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.caodeveloping.androgangnam.Main.onCreate(Main.java:388)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
... 11 more
And the 388th row is the out.close(); Is it possible that /sdcard/ is not suitable path on that phone? What could cause this? Thanks in advance!
Update, this?
String path= Environment.getExternalStorageDirectory().getAbsolutePath();
path += "/file.ogg";
Two problems:
a) Obviously, you are trying to close file (out.close()), event if you wasn’t able to open it
b) I would recommend to use Environment.getExternalStorageDirectory(), instead of hardcoded directory name “/sdcard”. It’s not guaranteed that SD card will be mounted to this path. That’s exactly the reason of Environment.getExternalStorageDirectory() API.
Also, I recommend to review this whole code for error handling (if something can’t be opened, read, etc.)