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.
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.
Related
I need to perform complex query with joins - seems to be too complex to use QueryBuilder, so I'll SQL my way around. I know however, that result of this query will be a list containing only a single entity type. Is there a way to leave mapping of results to ORMLite? Usually I parsed results myself, but in this case entity contains a lot of fields and I really don't want to go into parsing those from List<String[]>...
... that result of this query will be a list containing only a single entity type. Is there a way to leave mapping of results to ORMLite?
There certainly is. If you take a look at the "raw query" section of the documentation, you can see that it talks about the use of the RawRowMapper class. To quote from the docs:
You can also map the results into your own object by passing in a RawRowMapper object. This will call the mapping object with an array of strings and allow it to convert the strings into an object. The DAO provides a default RawRowMapper that can be gotten from orderDao.getRawRowMapper() that knows how to convert the string array into the object.
So for this you would call dao.queryRaw(...) with the RawRowMapper arg which maps from an array of strings. There are other dao.queryRaw(...) methods including:
queryRaw(String, DatabaseResultsMapper, String...) which allows you to map an object directly from the database results.
queryRaw(String, DataType[], RawRowObjectMapper, String...) which maps from an array of objects if you specify the result types.
Using Room ORM, I have declared an entity EQPreset using #Entity annotation. The entity contains an array int[]. It gives following error:
error: Cannot figure out how to save this field (int[] arr) into database. You can consider adding a type converter for it.
Normally saving EQPreset instance to a database, I would create a separate table to store values of the array and have a foreign key pointing to the relevant EQPreset.
However, I need to find what will be the way of storing this int[] arr of EQPreset using Room, that is, either by making a separate table or using any good approach/way.
Option #1: Get rid of int[] arr. Have some other entity represent this integer, with a foreign key back to the EQPreset entity. Have methods on your DAO be able to give you the integer-entities for a given EQPreset entity.
Option #2: Use a #TypeConverter to convert the int[] into something that can go into a single column (e.g., convert it to and from a JSON array, represented as a string).
I was curious if androids SQLiteDatabase insert method automatically handles type conversion.
Here is my example:
I have a csv file with a column name of age. Its type will be an INTEGER.
Lets say I have already created the database and table.
Now I am parsing the csv file with CSVReader, which parses each line and inserts each value into an index of a String[].
In order to insert each line of data into the database, I have to use a ContentValue object, which allows me to store values in it.
//Parse each line and store in line...
ContentValue values = new ContentValue();
values.put(KEY_AGE, line[1]); // Assume line[1] is the age
database.insert(table, null, values);
If I store the age value as a string (as seen above), and then insert it into the table, does Android handle the conversion to INTEGER before inserting it into the database?
I am asking this because I am trying to insert a bunch of tables into a database, and it looks much cleaner when I can just iterate through an array then explicitly state each put call, i.e:
Also if anyone has any design suggestions feel free to tell me.
CLEAN
int i = 0;
for(String s : TransitContract.Routes.COLUMN_ARRAY) {
values.put(s, line[i]);
i++;
}
UGLY
values.put(TransitContract.Routes.KEY_ROUTE_ID, line[0]);
values.put(TransitContract.Routes.KEY_AGENCY_ID, line[1]);
values.put(TransitContract.Routes.KEY_SHORT_NAME, line[2]);
values.put(TransitContract.Routes.KEY_LONG_NAME, line[3]);
values.put(TransitContract.Routes.KEY_DESCRIPTION, line[4]);
values.put(TransitContract.Routes.KEY_ROUTE_TYPE, Integer.parseInt(line[5]));
values.put(TransitContract.Routes.KEY_URL, line[6]);
values.put(TransitContract.Routes.KEY_COLOR, line[7]);
values.put(TransitContract.Routes.KEY_TEXT_COLOR, line[8]);
return mDatabase.insert(TransitContract.Routes.TABLE_NAME, null, values);
When you declare a column as INTEGER, SQLite will automatically convert strings to numbers, if possible.
See the documentation for Type Affinity.
If your ContentProvider doesn't restrict it (i.e. pass it directly to the SQLiteDatabase.insert() method), it should work. SQLite is not that picky about the types used in queries/inserts and the actual column type.
However, it would be best practice to parse and check the values before inserting. Otherwise you might actually insert a string which can't be parsed as integer and therefore retrieving the value might fail.
References:
Boolean datatype accepting string value and integer value
SQLite table with integer column stores string
I am having an arraylist of strings. I needt to store that arraylist in the 1 column of database.
How can I do that?
You can consider serializing an object into byte[] and saving it in your DB as a BLOB or going further encoding it in Base64 and saving as a TEXT. I'm not sure that any of these two are a good way to save your ArrayList - I'm just pointing options.
You might also consider creating other table and creating relation between them. There is a good pratice in databases called First Normal Form.
take a String, append arraylist's index string with the help of loop
String all="";
for(int i=0;i<arraylist.lenght;i++)
{
all=all+" "+ arraylist.get(i).tostring;
}
now store "all" in your DB field, only the problem with this is SIZE,
hope you got what i meant
Here's the situation. I have a bunch of objects that implement Serializable that I want to store in a SQL database. I have two questions
Is there a way to serialize the object directly into the database
Is that the best way to do it or should I
Write the object out to a formatting String and put it in the database that way and then parse it back out
Write each member to the database with a field that is unique to each object
Its generally not a good idea to try and put any sort of object (serialized/deliminated) in your SQL because modifying them is always a bitch.
It sounds like you're on the right track with idea 2. Is this a one-to-many situation? (because then a xref would obviously be the right answer) or even a foreign key would be better. cheers.
I'd still have a table per class + simplistic DAO.
If you absolutely want to do it wrong :), then serialize to JSON and persist the resulting string.
You could store the objects directly using db4o:
http://www.db4o.com/Android/default.aspx