2

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?

1 Answer 1

7

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;
  } 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks a lot! Do you now how I handle the relationships between the classes. Class A holds a list with Class B. Do I serialize each or just the "top" class?
Make both classes serializable. I think you just serialize class A.
Ok. And I save them as a blob?
There is no Blob in Sqlite, but yes it should work I think. Check: sqlite.org/datatype3.html , 2.1.3 for details. You can also save to disk, and example I pointed shows that.
BTW !!!! Wont it hit performance. If its json. why dont use just use json.ToString() function and store it to DB. and later on using JSONParser you can convert String to JSON.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.