Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Store a Parcelable Object in SQLite

I need to store an object content in Sqlite. I was wondering which was the best way to do it with a serialization of the object or with Parcelable.

Is it possible to store it as Parcelable? How can I do it?

like image 732
StErMi Avatar asked Jan 17 '12 14:01

StErMi


People also ask

Can we store object in sqlite?

You'll need to be able to serialize your object into a byte stream and then recreate your object from a byte stream. Then, just store that byte stream in your db.

How do I add a Parcelable?

Create Parcelable class without plugin in Android Studio implements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

What does Parcelable mean in Android?

A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.

What is a primary purpose of the Parcelable interface?

The Parcelable interface adds methods to all classes you want to be able to transfer between activities. These methods are how parcelable deconstructs the object in one activity and reconstructs it in another.


1 Answers

You are welcome to convert your object into some sort of persistable data structure (XML, JSON, Serializable) and stuff it in some database column. Bear in mind that you will still need to deal with compatibility issues (e.g., Version 2 of your app changes a class, which now needs to deal with both Version 1 and Version 2 structures). Also bear in mind that, going this route, you lose a lot of database capabilities (e.g., querying on something in the object).

You are also welcome to experiment with object databases, or CouchDb, or storing your persistable data structure to a file, if SQLite is not a requirement.

What most certainly will not work reliably is to pour the Parcelable into a Parcel and try storing the Parcel. A Parcel is meant for IPC use only and is not designed to be persisted. This is one of the reasons why Parcelable is faster than Serializable.

like image 146
CommonsWare Avatar answered Sep 27 '22 19:09

CommonsWare