简体   繁体   中英

Android - file writing in my onStop() method is crashing my app

I'm working on an android app, and when the app gets closed, I want it to save the contents of a specific array to a file, so that when the app is opened back up I can read the contents of it back into an array.

I could be wrong, but from my understanding, the method in which I should do this is the onStop() method.

The result is that when I hit the home button, the app closes and then gives me the "unfortunately, your app has crashed" message. I've tried running the debugger and my code seems to execute correctly up to and including the .close() command, but something after that seems to be happening. Below is my code, any help is much appreciated!

 @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();

    }
}

This is because you are not calling the onStop super class implementation. Quote from google API library:

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

So if you override Activity's onStop method, you must call super.onStop() at the start of the custom method. Try:

 @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();

    }
}

I would use the outputStreamWriter , it allows you to write strings to the file, rather than just bytes:

String test = "Test"; 

try{
   File outputFile = new File("your/file/name.txt");
   OutputStream outStream = new FileOutputStream(outputFile);
   OutputStreamWriter osWriter = new OutputStreamWriter(outStream);
   System.out.println("Writing data in file..!!");
   osWriter.write(str1);
   osWriter.close();
}
   catch(IOException OE){
    OE.getStackTrace();

}

Also, as noted by frogmanx, you need to include 'super.onStop()` in your method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM