Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store custom objects (User defined obj) in SQLite Android database

How can I store my custom object in a database ? To be more clear how do I write these statements.

To create a table, 1.

CREATE TABLE IF NOT EXISTS MY_TABLE(
        _id INTEGER PRIMARY KEY AUTOINCREMENT, customObject ??? NOT NULL);

What goes in the ????

To retrieve from a cursor,

2. MyObject obj = cursor.get???? What method can I use to get my stored object.

I googled a lot, but no luck. Do I need to store a serializable object? how?

Thanks in advance.

like image 555
dcanh121 Avatar asked Mar 06 '12 23:03

dcanh121


People also ask

Can you store objects 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 to store data in database in android?

Create a database using an SQL helper"DROP TABLE IF EXISTS " + FeedEntry. TABLE_NAME; Just like files that you save on the device's internal storage, Android stores your database in your app's private folder. Your data is secure, because by default this area is not accessible to other apps or the user.

Can we store ArrayList in SQLite Android?

Get the String from the SQLiteDatabse what you saved and changed into ArrayList type like below: outputarray is a String which is get from SQLiteDatabase for this example. Type type = new TypeToken<ArrayList<String>>() {}. getType(); ArrayList<String> finalOutputString = gson.


1 Answers

How can I store my custom object in a database ?

You don't, unless you are using an object database. You store a representation of the object in a database.

What goes in the ????

That depends on what your representation is. If you convert the object to XML or JSON, it would be TEXT. If you convert the object to a byte array (e.g., Serializable), you would use BLOB.

What method can I use to get my stored object.

That depends on what your representation is. If you converted the object to XML or JSON, use getString(). If you converted the object to a byte array, use getBlob().

Most developers would not do any of this, but rather would store the attributes of the object as individual columns, to allow for the greatest possible flexibility in querying the database.

like image 138
CommonsWare Avatar answered Sep 19 '22 11:09

CommonsWare