2014-05-10 5 views
7

è giusto. Ho questo gridview. Voglio salvare il suo oggetto come blob in sqlite. così quando ho aperto l'elenco di salvare i dati in malati SQLite basta caricare il salvataggio items e chiamare adapter.notifyDataSetChanged alla mia gridviewAndroid Salva oggetto come blob in sqlite

ho provato questo, ma ho NotSerializableException errore

Elenco articoli = 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; 
     } 
    } 

mia riga di inserimento

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

poi inserire l'oggetto serializzare

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

anche io sono confuso. dovrei salvare l'adattatore o l'elenco degli articoli?

risposta

21

Il modo in cui memorizzo i dati come BLOB nel mio DB, è convertirli in JSON e quindi memorizzare i byte. ad es.

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 

e per ottenere la lista di nuovo

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: per rispondere alla tua ultima domanda, è necessario memorizzare i dati (elenchi degli articoli).

+0

Cosa intendi? Come conservare un elenco di elementi? O come recuperarli? –

+0

come richiamarli – user3487657

+0

Modificato la risposta per dimostrare come recuperarli :) –