I’m quite inexperienced with using databases in applications, so I need a bit of guidance.
I have a Java object with several primitive fields, and several references to Strings and ArrayList objects. The primitives and Strings map nicely to available SQLite fields, but I’m not sure how I can persist the ArrayLists.
I was entertaining two ideas, one of which is to serialise the ArrayLists and store them in a Text field, the other is to have a column which points to a table with arity 1, in which I can store the individual strings, but I’m unsure of how to implement this in android. I’m open to different approaches, but I wouldn’t know how to implement the latter in java using SQLite, so a solution would be lovely. Thanks.
Generally (from what I have learned) if you have an object, which itself contains a list of other objects, that would be a 1 to many (or potentially many-to-many) relationship. To store this data you would want to use another table. In the other table, you will have your primary key for the object, and then a foreign key referencing the parent object to which it belongs. See this link for a better explanation.
Example:
Now say you have a user object, with a List of UserPictures’, when you save to the database you
will want to iterate over each picture and insert each one into the UserPicture table, using the
userId as the link back to the User table.
In the instance of a many-to-many relationship, each Object would have a List of their children objects.
A better example of this would be a Membership/Role system. A User would have a List of Roles, and a Role
would have a List of Users, since a user can (normally) be in multiple roles, and a role can of course have
multiple users. This would simply require whats called a join table I think it is. UserInRole would have two columns, UserID and RoleID to show that User X belongs to Role Y.
As far as how to implement it, search around for ‘Android sqlite tutorial’. Here and here are two links with tutorials on how to setup a sqlite android database app.