我正在开发一个 Android 应用程序,当应用程序关闭时,我希望它将特定数组的内容保存到一个文件中,这样当应用程序重新打开时我可以读取它的内容回到数组中。
我可能是错的,但根据我的理解,我应该在其中执行此操作的方法是 onStop() 方法。
结果是,当我按下主页按钮时,应用程序关闭,然后向我显示“不幸的是,您的应用程序已崩溃”消息。我试过运行调试器,我的代码似乎正确执行了 .close() 命令,但之后似乎发生了一些事情。以下是我的代码,非常感谢任何帮助!
@Override
public void onStop()
{
try{
FileOutputStream fOut = openFileOutput("savedVinyls", Context.MODE_PRIVATE);
String vinylString = "Test";
fOut.write(vinylString.getBytes());
fOut.close();
}
catch(IOException OE){
OE.getStackTrace();
}
}
最佳答案
这是因为您没有调用 onStop 父类(super class)实现。引用自谷歌 API 库:
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
所以如果你覆盖了Activity的onStop方法,你必须在自定义方法的开始调用super.onStop()。尝试:
@Override
public void onStop()
{
super.onStop();
try{
FileOutputStream fOut = openFileOutput("savedVinyls", Context.MODE_PRIVATE);
String vinylString = "Test";
fOut.write(vinylString.getBytes());
fOut.close();
}
catch(IOException OE){
OE.getStackTrace();
}
}
关于java - Android - 在我的 onStop() 方法中写入文件使我的应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18295012/