OVERTONE OVERTONE - 9 months ago 31
SQL Question

Simple Joined Table in SQLite on Android

I'm trying to do something simple here but my knowledge on databases and SQL is rusty at best.
I'm was following a tutorial here and am now trying to make my own joined table.

To explain a bit more simply, Profiles have widgets, widgets can be of multiple types.
The widget table contains an id, a name and a string widget_type. For each widget type, there will be another table for that widget_type.


Widget1 Widget2 Widget3

The part I'm having trouble with is sharing the Id's among the widgets so that they are unique across all 3 widget tables. Heres the SQL I have below but I'm not entirely sure what I'm trying to do is called or if it can be done from within SQLite

private static final String PROFILE_DATABASE_CREATE = "create table "
+ " integer primary key autoincrement, " + PROFILE_COLUMN_NAME
+ " text not null);";

// Widget creation SQL statement
private static final String WIDGET_DATABASE_CREATE = "create table "
+ TABLE_WIDGETS + "(" + COLUMN_ID +"integer primary key autoincrement" + WIDGET_COLUMN_TYPE +"text not null";

Answer Source

Urk. Hard to do this so that the IDs in Widget1 are different from the IDs in Widget2.

A more simple way is to collapse all the tables together. The Contacts Provider that backs the People application does this. Have one table containing the data for all three widget types. Differentiate a row for a particular widget type with a unique MIME type. Add a widget by adding it to the table with the _ID value of the profile it belongs to, the MIME type for its widget type, and its data.

The trick is to give this "generic widget" table the maximum number of columns you'd need for any type of widget. Provide some columns that are the same for any widget, and then some generic columns (say DATA1 through DATA5) whose contents vary according to the type of widget. Then assign type-specific constants for each widget type

For example, for the Widget table you'd create these column name constants

private static final String _ID = "_ID";
private static final String WIDGET_NAME = "name";
private static final String WIDGET_TYPE = "MIMEtype";


private static final String WIDGET1_TYPE = "vnd.example.com/widget1";
private static final String WIDGET2_TYPE = "vnd.example.com/widget2";
private static final String WIDGET3_TYPE = "vnd.example.com/widget3";


private static final String SOME_WIDGET1_COLUMN = "DATA1";
private static final String SOME_OTHER_WIDGET2_COLUMN = "DATA2";


It really doesn't matter if you retrieve a row of MIME type "vnd.example.com/widget1" and then access the cursor using "SOME_OTHER_WIDGET2_COLUMN", but it's easier to keep track of what's going on if you use the Widget1 constants on Widget1 cursors, etc.

If you've ever wondered what all the contract classes for android.provider do, well, this is it.