我正在尝试用我的android应用程序创建一个文件。我需要在一个特定的类中写入该文件。下面列出了我目前为它编写的代码。当nullpointerexception试图将写入文件时,我一直得到它。准确的错误列在下面。我是android的新手,所以请详细说明。
谁能告诉我我做错了什么,我如何解决这个问题?
//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)发布于 2011-04-04 23:54:08
下面的代码是我计算出来的,并且正在起作用。很抱歉花了这么长时间才发出去。
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();
}
}
}发布于 2011-03-26 02:12:44
看起来,您正在构造函数中执行此操作。你不能这么做。您需要等到onCreate(),即当您知道对象已经初始化时。
发布于 2011-03-26 00:16:25
你应该通过内容提供者访问文件,我认为路径是错误的.看看这个文件教程
https://stackoverflow.com/questions/5439240
复制相似问题