johan
johan

Reputation: 6666

Storing large ArrayLists to SQLite

I im developing a application in which I continuously download large amount of data.

The data in json format and I use Gson to deserialize it. By now Im storing this in a SQLite db. And I have to calculate the relationship and store them into a relationship db. However this takes too much time.

It would be much more convenient to save the class objects to db.

The data looks something like this after deserialization:

Class A{
private String name;
private List<B> subItems;
}

Class B{
private String name;
private List<C> subItems
}

Can I persist this in a easier way, for example by making them serializable? How can this be done?

Upvotes: 2

Views: 3617

Answers (1)

Caner
Caner

Reputation: 59288

Yes, serialization is a better solution in your case and it works in Android. The following example is taken from http://www.jondev.net/articles/Android_Serialization_Example_%28Java%29

serialization method:

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

deserialization method:

  public static Object deserializeObject(byte[] b) { 
    try { 
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b)); 
      Object object = in.readObject(); 
      in.close(); 

      return object; 
    } catch(ClassNotFoundException cnfe) { 
      Log.e("deserializeObject", "class not found error", cnfe); 

      return null; 
    } catch(IOException ioe) { 
      Log.e("deserializeObject", "io error", ioe); 

      return null;
  } 

Upvotes: 7

Related Questions