cstrutton cstrutton - 1 year ago 168
Android Question

How do I store a bundle in a database blob?

Ive been searching google for a way to convert a

into a string suitable to store in a database as a
type. I have found lots of examples of serializing it to a file but no mention of how to put it into a string or byte aray. Can anyone give me an example of how this is done?

I am developing an app that will use plugin's for custom UI components and want to call a configuration activity in the plugin passing a bundle of configuration options that were stored in a database. The activity would return the bundle with the updated options and then I need to save it back to the database.

If anyone can point me in the right direction I would be grateful.

Answer Source

Your first step is to create a table to put this in. In this case something basic should do.

CREATE TABLE bundles (
    name TEXT, 
    value BLOB);

Then you will need a method for inserting the Bundle, like this:

private void put(SQLiteDatabase db, String name, Bundle bundle) {
    ByteArrayOutputStream valueStream = new ByteArrayOutputStream();
    try {
        ContentValues rows = new ContentValues();
        rows.put("name", name);
        Parcel p = Parcel.obtain();
        bundle.writeToParcel(p, 0);

        rows.put("value", valueStream.toByteArray());

        db.insert("bundles", null, rows);   

    } catch (IOException e) {       
        Log.e("error writing object", e.toString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download