문제

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

I tried this one but I get 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 row

public long insertRow(byte[] data) {
    /*
     * CHANGE 3:
     */
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's 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));

also i'm confuse. should i save the adapter or the list of items'?

도움이 되었습니까?

해결책

The way I store data as BLOB in my DB, is by converting them to JSON and then storing the bytes. e.g.

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 get the list back

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: to answer your last question, you should store your data (list of items).

다른 팁

instead of (Object o), pass (Serializable o). Then, in the stuff you pass, add implements Serializable to class definition.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top