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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With