Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save bundle to file

Tags:

android

  Bundle bundle;
  //set data to bundle
  //......


  File file = new File(context.getFilesDir().getAbsolutePath()  + "/data/");
                FileOutputStream fos;
                try {
                     fos = new FileOutputStream(file);
                     //fos.write
                     fos.close();
                } catch (FileNotFoundException exp1) {
                    exp1.printStackTrace();
                } catch ( IOException exp2) {
                    exp2.printStackTrace();
                }

I have the aforementioned code. All I want to do is to save the bundle to the file. I found the method write but I can't pass there a bundle but only a byte[].I tried to convert the bundle to byte[] but I didn't succeed it. What Should I do to make this work? What is the most efficient way?

like image 922
Alex Dowining Avatar asked Jan 10 '13 11:01

Alex Dowining


2 Answers

There is no general way to save and restore bundle from persistent storage. This is because Parcel class doesn't give any android version compatibility guarantee. So we better not serialize it.

But if you really want you can searialize Bundle via Parceable interface. Convert bundle to a Parcel (writeToParcel()/readFromParcel()), then use Parcel's marshall() and unmarshall() methods to get a byte[]. Save/Load byte Array to file. But there is a chance, that one day you wont be able to restore your data in case user updates his Android OS to a newer version.

There is one legal but very paifull and unreliable way to serialize bundle using ObjectOutput/InputStream. (get all keys, iterate through keys and save serializable key=value pairs to a file, then read key=value pair from file, determine value's type, put data back in Bundle via appropriate putXXX(key, value) method) But it is not worth it )

I suggest you to put your custom serializable structure in Bundle to store all required values in it and save/load from file only this structure.

Or find a better way to manage your data without using Bundle.

like image 132
Leonidos Avatar answered Sep 28 '22 15:09

Leonidos


I didn't like the formatting of the code in my comment above, so this is how you would read it back out:

Read it like this:

try {
    FileInputStream fis = openFileInput(localFilename);
    byte[] array = new byte[(int) fis.getChannel().size()];
    fis.read(array, 0, array.length);
    fis.close();
    parcel.unmarshall(array, 0, array.length);
    parcel.setDataPosition(0);
    Bundle out = parcel.readBundle();
    out.putAll(out);
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
} finally {
    parcel.recycle();
}
like image 35
videogameboy76 Avatar answered Sep 28 '22 14:09

videogameboy76