Android Save object as blob in sqlite

- this is right. I have this gridview . I want to save its element as blob in sqlite. so when i open the list of save data in sqlite just load save items and call adapter.notifyDataSetChanged on my gridview

I tried this, but getting a NotSerializableException error

List items = new ArrayList ();

 public static byte[] serializeObject(Object o) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(o); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); return buf; } catch (IOException ioe) { Log.e("serializeObject", "error", ioe); return null; } } 

my insert line

 public long insertRow(byte[] data) { /* * CHANGE 3: */ // TODO: Update data in the row with new fields. // TODO: Also change the function arguments to be what you need! // Create row data: ContentValues initialValues = new ContentValues(); initialValues.put(KEY_DATA, data); // Insert it into the database. return db.insert(DATABASE_TABLE, null, initialValues); } 

then i insert the serialize object

 myDB.insertRow(MyDBAdapter.serializeObject(items)); 

I am also confused. Should I save an adapter or list of items?

+7
android sqlite gridview
source share
1 answer

The way to store data as a BLOB in my database is to convert it to JSON and then store the bytes. eg.

 ArrayList<Person> persons = new ArrayList<>(); Gson gson = new Gson(); ContentValues values = new ContentValues(); values.put(MyProvider.KEY_DATA, gson.toJson(persons).getBytes()); // insert or update the DB 

And to return the list

 byte[] blob = cursor.getBlob(cursor.getColumnIndex(MyProvider.KEY_DATA)); String json = new String(blob); Gson gson = new Gson(); ArrayList<Person> persons = gson.fromJson(json, new TypeToken<ArrayList<Person>>() {}.getType()); 

Edit: in order to answer your last question, you must save your data (list of items).

+21
source share

All Articles