Save package to file

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 above code. All I want to do is save the package in a file. I found the write method, but I cannot pass the packet there, but only the byte []. I tried to convert the packet to byte [], but I failed. What should I do to make this work? What is the most effective way?

+4
source share
7 answers

There is no general way to save and restore a package from persistent storage. This is due to the fact that the Parcel class does not guarantee the compatibility of Android versions. Therefore, we better not serialize it.

But if you really want to, you can sublimate the Bundle through the Parceable interface. Convert the package to a parcel (writeToParcel () / readFromParcel ()), then use the Parcel marshall () and unmarshall () methods to get the byte []. Save / load byte array to file. But there is a chance that one day you will not be able to restore your data if the user updates their Android OS to a newer version.

There is one legitimate, but very simple and unreliable way to serialize a package using ObjectOutput / InputStream. (get all the keys, iterate over the keys and save the serializable key = value pairs to a file, then read the key = pair value from the file, determine the type of value, put the data back into the Bundle using the appropriate putXXX (key, value) method). But it is not worth it)

I suggest you put your custom serializable structure in the Bundle, to save all the necessary values ​​in it and save / load only this structure from the file.

Or find the best way to manage your data without using the Bundle.

+4
source

I did not like the formatting of the code in my comment above, so here is how you would read it:

Read it as follows:

 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(); } 
+4
source
 Bundle in=yourBundle; FileOutputStream fos = context.openFileOutput(localFilename, Context.MODE_PRIVATE); Parcel p = Parcel.obtain(); //creating empty parcel object in.writeToParcel(p, 0); //saving bundle as parcel fos.write(p.marshall()); //writing parcel to file fos.flush(); fos.close(); 
+3
source

You can do something like this

 public void write(String fileName, Bundle bundle) { File root = Environment.getExternalStorageDirectory(); File outDir = new File(root.getAbsolutePath() + File.separator + "My Bundle"); if (!outDir.isDirectory()) { outDir.mkdir(); } try { if (!outDir.isDirectory()) { throw new IOException("Unable to create directory My bundle. Maybe the SD card is mounted?"); } File outputFile = new File(outDir, fileName); writer = new BufferedWriter(new FileWriter(outputFile)); String value=bundle.getString("key"); writer.write(value); Toast.makeText(context.getApplicationContext(), "Report successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); writer.close(); } catch (IOException e) { Log.w("error", e.getMessage(), e); Toast.makeText(context, e.getMessage() + " Unable to write to external storage.", Toast.LENGTH_LONG).show(); } } 

The idea here is simple. You pass the Bundle this method, and then extract all the data that you have (for example, in this case we have a line with the key key ), and then write it to a file.

0
source

Here is a function that can help you convert a Bundle to a JSONObject , note that it will only work if the package contains int and String only

 public static JSONObject bundleToJsonObject(Bundle bundle) { try { JSONObject output = new JSONObject(); for( String key : bundle.keySet() ){ Object object = bundle.get(key); if(object instanceof Integer || object instanceof String) output.put(key, object); else throw new RuntimeException("only Integer and String can be extracted"); } return output; } catch (JSONException e) { throw new RuntimeException(e); } } public static Bundle JsonObjectToBundle(JSONObject jsonObject) { try { Bundle bundle = new Bundle(); Iterator<?> keys = jsonObject.keys(); while( keys.hasNext() ){ String key = (String)keys.next(); Object object = jsonObject.get(key); if(object instanceof String) bundle.putString(key, (String) object); else if(object instanceof Integer) bundle.putInt(key, (Integer) object); else throw new RuntimeException("only Integer and String can be re-extracted"); } return bundle; } catch (JSONException e) { throw new RuntimeException(e); } } 
0
source

You cannot save the package in a local file. You will get an exception without serialization. There may be other shortcuts for storage. After reading and creating the original object is not 100% guaranteed.

0
source

I think the best idea is static serialization or all, since the Bundle is iterated from keys, serialized and unesterified on the other hand, you can use json or something else. For example, if you use the same class on the server and the recipient, ...

bundle-> serializable_object-> json-> file-> serializable_object-> bundle

any version of os guaranteed to work

0
source

All Articles