2014-05-10 18 views
7

là đúng. Tôi có số này gridview. Tôi muốn lưu mục của nó như là blob trong sqlite. vì vậy khi tôi mở danh sách lưu dữ liệu trong sqlite bệnh chỉ cần tải lưu items và gọi adapter.notifyDataSetChanged để tôi gridviewAndroid Lưu đối tượng dưới dạng blob trong sqlite

tôi đã cố gắng này nhưng tôi nhận NotSerializableException lỗi

Danh sách

mục = 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; 
     } 
    } 

hàng chèn của tôi

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); 
} 

sau đó tôi chèn các đối tượng serialize

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

cũng tôi nhầm lẫn. tôi có nên lưu bộ điều hợp hoặc danh sách các mục 'không?

Trả lời

21

Cách tôi lưu trữ dữ liệu dưới dạng BLOB trong DB của tôi, bằng cách chuyển đổi chúng thành JSON và sau đó lưu trữ các byte. ví dụ:

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 

Và để có được danh sách mặt sau

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: để trả lời câu hỏi cuối cùng của bạn, bạn nên lưu trữ dữ liệu của bạn (danh sách các mục).

+0

Ý của bạn là gì? Làm thế nào để lưu trữ một danh sách các mục? Hoặc làm thế nào để lấy lại chúng? –

+0

cách lấy lại – user3487657

+0

Đã chỉnh sửa câu trả lời để chứng minh cách lấy lại :) –

Các vấn đề liên quan