I am facing this error when I try to write objects to a file.
02-05 11:31:41.818: W/System.err(2414): java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[], int, int)' on a null object reference
02-05 11:31:41.818: W/System.err(2414): at java.io.DataOutputStream.writeShort(DataOutputStream.java:192)
02-05 11:31:41.818: W/System.err(2414): at java.io.ObjectOutputStream.writeStreamHeader(ObjectOutputStream.java:1795)
02-05 11:31:41.818: W/System.err(2414): at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:271)
02-05 11:31:41.818: W/System.err(2414): at com.data.mydata.addData(addData.java:173)
The line 173 which shows the error is oos = new ObjectOutputStream(fileStream);
My code is -
path = Environment.getExternalStorageDirectory()
+ File.separator + "Documents";
path += File.separatorChar + "Sensor Data";
Log.d("hi", "path = " + path);
File file = new File(path, filename);
new File(path).mkdirs();
try {
file.createNewFile();
fileStream = new FileOutputStream(filename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//AllData extends Serializable
List<AllData>valuelist = new ArrayList<AllData>(sensor.values());
if(valuelist.size() != 5){
try {
//fileStream = new FileOutputStream(filename);
oos = new ObjectOutputStream(fileStream);
oos.writeObject(valuelist);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Basically when my size of arraylist is not equal to 5, I need to keep writing to the file and once its 5, I need to stop it. My file is created properly in SDCard in Documents/Sensor Data/myfile.txt . Could you please help me how do I resolve this error?