How do you store a collection of rows in SQLite on Android?

I am pretty inexperienced with using databases in applications, so I need some tips.

I have a Java object with several primitive fields and some references to String and ArrayList objects. Primitives and strings are familiar with the available SQLite fields, but I'm not sure how I can save ArrayLists.

I worked on two ideas, one of which is to serialize ArrayLists and save them in a text box, and the other is a column that points to a table with arity 1, in which I can store individual rows, but I'm not sure how to implement this in Android. I am open to different approaches, but I don’t know how to implement the latter in java using SQLite, so the solution will be fine. Thank.

+5
source share
2 answers

As a rule (from what I learned), if you have an object that itself contains a list of other objects, this will be a 1 to many (or potentially many to many) relationship. To save this data, you want to use another table. In another table, you will have your primary key for the object, and then the foreign key that refers to the parent object to which it belongs. See this link for a better explanation.

Example:

CREATE TABLE User (
    _id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name TEXT

);

CREATE TABLE UserPicture(
    _id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    userId INTEGER,
    path TEXT

FOREIGN KEY(userId) REFERENCES User(_id)
);

, UserPictures ', , UserPicture, userId User.

" " . /. , () , , , . , , , . UserInRole : UserID RoleID, , X Y.

, , "Android sqlite tutorial". - sqlite android database.

+7

, , , , .

, ,

String name;
int age;
ArrayList<String> hobbies;

:

create table person (personid int, name varchar(30), age int);
create table hobby (hobbyid int, personid int, description varchar(30));

:

Person
11   Bob    18
12   Sally  68
13   Ford   42

Hobby
21   11   fishing
22   11   hunting
23   12   needlepoint
24   12   rock-climbing
25   13   hitch-hiking   

, , :

select person.name, hobby.description
from person
join hobby on person.personid=hobby.personid
+9

All Articles