gpt4 book ai didi

java - 在安卓上创建一个文件

转载 作者:行者123 更新时间:2023-12-02 00:44:13 25 4
gpt4 key购买 nike

我正在尝试使用我的 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)

最佳答案

看起来您正在构造函数中执行此操作。你不能那样做。您需要等到 onCreate(),此时您知道该对象已初始化。

关于java - 在安卓上创建一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5439240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com