I am trying to create a file with my android application. I need to write to the file in a specific class. The code I currently have for it is list开发者_如何转开发ed below. I keep getting a nullpointerexception
when it is trying to write to the file. The exact error is listed below. I am new to android, so please be detailed.
Can someone please tell me what I am doing wrong and how i can fix this issue?
//the class where i need to create and write to the file
public class DataRobot {
Context tThis;
FileOutputStream fOut;
OutputStreamWriter writer;
public DataRobot(SmartApp smartApp) extends Activity {
tThis = (Context) smartApp;
}
public void onCreate(Bundle savedInstanceState) {
try {
//file = new File("/sdcard", "test.csv");
fOut = openFileOutput("test.csv", MODE_WORLD_READABLE);
writer = new OutputStreamWriter(fOut);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void analyzeData(SmartDataObject temp) {
data = temp;
try {
//the following line is where the error is occurring.
writer.write(Double.toString(data.getHeartRate()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//the error
03-26 03:47:53.924: WARN/System.err(273): java.lang.NullPointerException
03-26 03:47:53.934: WARN/System.err(273): at cpe495.smartapp.DataRobot.analyzeData(DataRobot.java:80)
03-26 03:47:53.946: WARN/System.err(273): at cpe495.smartapp.SmartApp$1.dataReceivedReceived(SmartApp.java:49)
03-26 03:47:53.956: WARN/System.err(273): at cpe495.smartapp.ConnectDevice.fireDataReceivedEvent(ConnectDevice.java:79)
03-26 03:47:53.956: WARN/System.err(273): at cpe495.smartapp.ConnectDevice.run(ConnectDevice.java:46)
03-26 03:47:53.965: WARN/System.err(273): at java.lang.Thread.run(Thread.java:1096)
It looks like you are doing this in your constructor. You can't do that. You need to wait until onCreate(), which is when you know the object has been initialized.
You should acces files via content providers, I think the path is wrong... look at this file tutorial
The following code is what i figured out and is working. Sorry it took so long to post.
public class DataRobot {
Context tThis; //was enabled for preferences
private FileOutputStream fOut;
private OutputStreamWriter writer;
public DataRobot(SmartApp smartApp) {
tThis = (Context) smartApp;
}
public void analyzeData(SmartDataObject temp) {
try {
fOut = tThis.openFileOutput("test.csv", tThis.MODE_APPEND);
writer = new OutputStreamWriter(fOut);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.write("Test");//0
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
精彩评论