ta1130 ta1130 - 1 month ago 6
Android Question

Syntax error with SQLite query in Android

I am trying to create a new SQLite database in Android.
Here is my onCreate method:

public static final String DATABASE_NAME = "eventList.db";
public static final String TABLE_NAME = "event_table";
public static final String COL1 = "ID";
public static final String COL2 = "EVENTNAME";
public static final String COL3 = "UNIXTIMESTAMP";
public static final String COL4 = "PARTICIPANTS";
public static final String COL5 = "LOCATION";
public static final String COL6 = "LOCATIONNAME";
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCRIMENT, "
+ " EVENTNAME TEXT, UNIXTIMESTAMP INTEGER, PARTICIPANTS TEXT, LOCATION TEXT, LOCATIONNAME TEXT)";
sqLiteDatabase.execSQL(createTable);
}


This is throwing a syntax error:


android.database.sqlite.SQLiteException: near "AUTOINCRIMENT": syntax error (code 1): , while compiling: CREATE TABLE event_table(ID INTEGER PRIMARY KEY AUTOINCRIMENT, EVENTNAME TEXT, UNIXTIMESTAMP INTEGER, PARTICIPANTS TEXT, LOCATION TEXT, LOCATIONNAME TEXT)


Please do note that PARTICIPANTS is going to be a custom object, and LOCATION is going to be a LatLng object.

How can I solve the error?

Answer Source

You have a typo in

 String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCRIMENT, "

Note that AUTOINCRIMENT should be spelt AUTOINCREMENT

plus ID should be _id Also, as you have gone to the trouble of setting up constants why not use them to save on further potential typos? e.g. Instead of

+ " EVENTNAME TEXT

Why not use

+ COL2 + " TEXT

etc...

Could I suggest you read up on how to create databases here It is a superb tutorial and shows best practices