user2050387
user2050387

Reputation: 1

Android SQLite and object in a class

The question has already been asked but I can't find a similar problem.

I have to class :

public class Categorie {

// Attributs
private int identifiant;
private String libelle;

...
}

And

public class Restaurant {

// Attributs
private int identifiant;
private String nom;
private String description;
private List<Categorie> lesCategories;

...
}

But with SQLite, I don't know how tu use "lesCategories"..

I have read this tutorial in french :

In SQLite the object type does not exist.. Only String, Integer, Real, Blob.

For be more explicite : I have a problem with my cursor it's here --> "????":
Because, it's not a String or Int but object..

public Restaurant ConvertCursorToObject(Cursor c) { Restaurant restaurant= new Restaurant ( c.getInt(EnseigneOpenHelper.NUM_RES_ID), c.getString(EnseigneOpenHelper.NUM_RES_NOM), c.getString(EnseigneOpenHelper.NUM_RES_DESCRIPtion), ????
); return restaurant; }

/** * Convert a cursor in Restaurant */

public Restaurant ConvertCursorToOneObject(Cursor c) { c.moveToFirst(); Restaurant restaurant = ConvertCursorToObject(c); c.close(); return restaurant ; }

Upvotes: 0

Views: 1270

Answers (1)

Martijn
Martijn

Reputation: 13622

I’m assuming that the question you’re (not) asking is this: how to save the information contained in these two classes to a relational database.

You can’t save an object in a SQL database (unless as a BLOB), and anyway, that’s not what you should be doing here. You need to normalize your data.

What you need here, is three tables:

  1. The first table, called Categorie;
  2. A second table called Restaurant;
  3. A third table called RestaurantCategorie;

The third table will contain only two fields: categorie_id and restaurant_id. Each row will list a valid combination of a restaurant and a category. That table will contain the values corresponding to the property lesCategories.

Here’s an example of the relevant SQL:

CREATE TABLE Categorie
( categorie_id  INTEGER PRIMARY KEY
, libelle       TEXT    NOT NULL
);

CREATE TABLE Restaurant
( restaurant_id INTEGER PRIMARY KEY
, nom           TEXT    NOT NULL
, description   TEXT
);

CREATE TABLE RestaurantCategorie
( restaurant_id INTEGER NOT NULL    REFERENCES Restaurant
, categorie_id  INTEGER NOT NULL    REFERENCES Categorie
, PRIMARY KEY (restaurant_id, categorie_id)
);

If you want to understand why, you should to do some reading on the topics of relational database design, data modeling, and most especially: database normalization (most notably the examples).

The reason you couldn’t find this on StackOverflow is probably because this is very basic stuff when working with SQL databases.

Upvotes: 3

Related Questions