views:

37

answers:

1

I'm trying to save an object in a file but the file doesn't appear on the device and I don't get an exception either.

public static void save(Context ctx) {
    Log.i("App serialization", "Saving to settings.ser: " + ctx.getFileStreamPath("settings.ser"));
    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
        fos = ctx.openFileOutput("settings.ser", Context.MODE_PRIVATE);
        out = new ObjectOutputStream(fos);
        out.writeObject(ApplicationData.settings);
        out.flush();
        out.close();
        //fos.close();
        Log.i("App serialization", "Finished writing to settings.ser");
    }
    catch(IOException ex) {
        ex.printStackTrace();
        Log.e("App serialization", "Could not save to settings.ser");
    }
}

If instead I use:

try {
        fos = new FileOutputStream("/data/data/APP_PACKAGE/settings.ser");
        out = new ObjectOutputStream(fos);

It works and I can see that the file has been created on the device.

But this isn't cool and it's not the way to do it because the directory structure may change in the future.

A: 

First, get rid of the printStackTrace() call, and supply your IOException object to android.util.Log instead (e.g., third parameter in your e() call).

Second, /data/data/APP_PACKAGE/settings.ser is not where your file will wind up in your first code listing. It will go into /data/data/APP_PACKAGE/files/settings.ser.

Third, /data/data/APP_PACKAGE/settings.ser may not be a valid path on Android 2.2 when your app is installed on SD.

CommonsWare
1st - thanks2nd and 3rd - i know about that; That's what I said in the last sentece of my post. It won't work if I try to write in the /files subdir, but it will if I write in the app package dir.
Auras
Try building a new emulator image or something. There is no way you can write to where you are and not be able to write to `files/`. However, if the only way you have tried writing to `files/` is via your `save()` method above, perhaps try a different `Context`. For example, if the `Context` you are using is from `getApplicationContext()`, replace that with just the `Activity` or `Service` that was calling `getApplicationContext()` in the first place.
CommonsWare
It's funny because I use the same Context to download a file to the files/ dir using openFileOutput() and FileOutputStream elsewhere in the code.
Auras