cstrutton cstrutton - 1 month ago 17
Android Question

How do I store a bundle in a database blob?

Ive been searching google for a way to convert a

bundle
into a string suitable to store in a database as a
BLOB
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

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

CREATE TABLE bundles (
    _id INTEGER PRIMARY KEY AUTOINCREMENT, 
    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);

        valueStream.write(p.marshall());
        rows.put("value", valueStream.toByteArray());

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

        valueStream.close();
    } catch (IOException e) {       
        Log.e("error writing object", e.toString());
    }
}
Comments