Search code examples
androidloadsaveoncreateonpause

Android Beginner Save/Load small information


I am looking to save/load a very easy application in android. The thought would be checking if a file exists in the onCreate() method and if it does load the settings in onCreate. Is this the right function to do this in? Saving is done in the onPause() function.

The way I would be doing it is via FileOutputStream and FileInputStream.

But how does my code look then? Currently I have this:

if (new File(FILENAME).isFile()) {
        FileInputStream fis = null;
        try {
            fis = openFileInput(FILENAME);
            fis.read();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        numOfEpisode = Integer.parseInt(fis.toString());
        numOfSeason = Integer.parseInt(fis.toString());
    }

Ignore the fact that I haven't handled the exceptions yet, since I know the file will be there when testing.

protected void onPause() {
    try {
        FileOutputStream fos = openFileOutput(FILENAME,
                Context.MODE_PRIVATE);
        fos.write(numOfEpisode);
        fos.write(numOfSeason);
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The App currently gives me an error when I close the app(when onPause() is called). Could anyone point me in any direction to why?

Also how do I know in what way FileOutputStream.write() writes my statements? Is this FIFO or LIFO?


Solution

  • I would use SharedPreferences for this as it's much easier to do and is specifically designed for storing and retrieving small amounts of information from the device. Check out How to use SharedPreferences in Android to store, fetch and edit values to see how this is done.

    You would read the values in onCreate and store them. When you onPause you would then write them out to SharedPreferences.