SQLite insert into error (Android) - java

Error
12-22 14:30:52.329 1261-1261/com.TrackApp.trackapp E/SQLiteLog﹕ (1) near "Throw": syntax error
12-22 14:30:52.329 1261-1261/com.TrackApp.trackapp D/AndroidRuntime﹕ Shutting down VM
12-22 14:30:52.339 1261-1261/com.TrackApp.trackapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
12-22 14:30:52.389 1261-1261/com.TrackApp.trackapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.database.sqlite.SQLiteException: near "Throw": syntax error (code 1): , while compiling: INSERT INTO Athletes (ID, First_Name, Last_Name, Age, Gender, Event, Tier) VALUES (0, Joe, Richards, 20, Male, Discus Throw, 2);
I keep getting this error when trying to add a new athlete to my database. Could someone please figure out what I am doing wrong. I am almost certain all of my sql statements are correct. I think it thinks that it is creating a new column under events for whatever is from the athlete object but I don't know
private static final String DATABASE_NAME = "AthletesDB";
private static final int VERSION = 1;
private static final String TABLE_NAME = "Athletes";
private static final String COLUMN_ID = "ID";
private static final String COLUMN_FIRST_NAME = "First_Name";
private static final String COLUMN_LAST_NAME = "Last_Name";
private static final String COLUMN_AGE = "Age";
private static final String COLUMN_GENDER = "Gender";
private static final String COLUMN_EVENT = "Event";
private static final String COLUMN_TIER = "Tier";
private static final String[] COLUMNS = {"ID", "First_Name", "Last_Name", "Age", "Gender", "Event", "Tier"};
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + "( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_FIRST_NAME + " VARCHAR(20), " + COLUMN_LAST_NAME + " VARCHAR(20), " + COLUMN_AGE + " INTEGER, " +
COLUMN_GENDER + " VARCHAR(20), " + COLUMN_EVENT + " VARCHAR(20), " + COLUMN_TIER + " INTEGER " + ")";
public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CREATE);
onCreate(db);
}
public void addAthlete(Athlete athlete){
SQLiteDatabase db = this.getWritableDatabase();
/*ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, athlete.getID());
contentValues.put(COLUMN_FIRST_NAME, athlete.getFirstName());
contentValues.put(COLUMN_LAST_NAME, athlete.getLastName());
contentValues.put(COLUMN_AGE, athlete.getAge());
contentValues.put(COLUMN_GENDER, athlete.getGender());
contentValues.put(COLUMN_EVENT, athlete.getEvent());
contentValues.put(COLUMN_TIER, athlete.getTier());*/
// db.insert(TABLE_NAME, null, contentValues);
db.execSQL("INSERT INTO " + TABLE_NAME + " (" + COLUMN_ID + ", " + COLUMN_FIRST_NAME + ", " + COLUMN_LAST_NAME
+ ", " + COLUMN_AGE + ", " + COLUMN_GENDER + ", " + COLUMN_EVENT + ", " + COLUMN_TIER + ")" +
" VALUES " + "(" + athlete.getID() + ", " + athlete.getFirstName()
+ ", " + athlete.getLastName() + ", " + athlete.getAge() + ", " + athlete.getGender() + ", " +
athlete.getEvent() + ", " + athlete.getTier() + ");");
db.close();
}

You should surround the string values you insert with single quotes. The exception is thrown because you have whitespace in your literal "Discus Throw". Try the following:
db.execSQL("INSERT INTO "
+ TABLE_NAME + " ("
+ COLUMN_ID + ", "
+ COLUMN_FIRST_NAME + ", "
+ COLUMN_LAST_NAME + ", "
+ COLUMN_AGE + ", "
+ COLUMN_GENDER + ", "
+ COLUMN_EVENT + ", "
+ COLUMN_TIER + ")" +
" VALUES " + "("
+ athlete.getID() + ", "
+ athlete.getFirstName() + ", "
+ athlete.getLastName() + ", "
+ athlete.getAge() + ", "
+ athlete.getGender() + ", "
+ "'" + athlete.getEvent() + "'" + ", "
+ athlete.getTier() + ");");
which gives you
INSERT INTO Athletes (ID, First_Name, Last_Name, Age, Gender, Event, Tier)
VALUES (0, Joe, Richards, 20, Male, 'Discus Throw', 2);

Surround each entry of type TEXT in VALUES with single quotes.
For example,
" VALUES ('" + athlete.getFirstName() + "')"
Or, written out:
" VALUES ('Bob')"

Related

SQLite create table

Im unable to create SQLite table.
Android Studio IDE shows me error on this line "Column constrains or Comma expected, got Text"
String CREATE_TABLE_CONTACTS = "CREATE TABLE " + Util.TABLE_NAME + "(" +
Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT," +
Util.KEY_PHONE_NUMBER + " TEXT" + ")";
IMO your code
String CREATE_TABLE_CONTACTS = "CREATE TABLE " + Util.TABLE_NAME + "(" +
Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT," +
Util.KEY_PHONE_NUMBER + " TEXT" + ")";
is ok problems belongs from Util.TABLE_NAME or Util.KEY_ID check here these key strings not having spaces
DO => user_name
DON'T => user name
If your columns happen to have whitespace or other reserved words, then you may try escaping them using double quotes:
String CREATE_TABLE_CONTACTS = "CREATE TABLE \"" + Util.TABLE_NAME + "\" (" +
"\"" + Util.KEY_ID + "\" INTEGER PRIMARY KEY, \"" + Util.KEY_NAME + "\" TEXT, \"" +
Util.KEY_PHONE_NUMBER + "\" TEXT" + ")";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "addToCart_db";
public static final String TABLE_NAME = "addToCart";
public static final String COLUMN_ID = "id";
public static final String COLUMN_PRODUCT_ID = "product_id";
public static final String COLUMN_QTY = "qty";
public static final String COLUMN_PRICE = "price";
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PRODUCT_ID + " TEXT,"
+ COLUMN_PRICE + " TEXT,"
+COLUMN_QTY +" TEXT)";
try it, this formatting create table

SQLiteException no such table, am I missing something?

I have researched other instances of this error all morning but nothing i've tried so far has worked. It could be something obvious as I am quite new to this.
I am trying to return the results of the GET_ALL_INGREDIENTS query. Which I will then put into a 2d array, but you don't need to worry about that. My TABLE_RECIPES table works fine.
SQLiteException: no such table: TABLE_INGREDIENTS (code 1): , while compiling: SELECT INGR...etc....
Which occurs on the last line of this bit of code:
public String[][] getRecipeIngredients(int id) {
String GET_ALL_INGREDIENTS = "SELECT INGREDIENT_NAME, INGREDIENT_QUANTITY, INGREDIENT_UNIT " +
"FROM TABLE_INGREDIENTS " +
"INNER JOIN TABLE_RECIPE_INGREDIENTS ON TABLE_RECIPE_INGREDIENTS.INGREDIENT_ID=TABLE_INGREDIENTS.INGREDIENT_ID " +
"WHERE RECIPE_INGREDIENTS.RECIPE_ID=" + id;
db = new MyDBHandler(mContext);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(GET_ALL_INGREDIENTS, null);
Table Creation:
final String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " +
TABLE_RECIPES + "(" +
RECIPE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RECIPE_NAME + " TEXT, " +
RECIPE_INSTRUCTIONS + " TEXT " +
")";
final String CREATE_TABLE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
TABLE_INGREDIENTS + "(" +
INGREDIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
INGREDIENT_NAME + " TEXT NOT NULL UNIQUE " +
")";
final String CREATE_TABLE_RECIPE_INGREDIENTS = "CREATE TABLE IF NOT EXISTS " +
TABLE_RECIPE_INGREDIENTS + "(" +
RECIPE_ID + " INTEGER NOT NULL, " +
INGREDIENT_ID + " INTEGER NOT NULL, " +
INGREDIENT_QUANTITY + " REAL, " +
INGREDIENT_UNIT + " TEXT, " +
"PRIMARY KEY (" + RECIPE_ID + "," + INGREDIENT_ID + "), " +
"FOREIGN KEY (" + RECIPE_ID + ") REFERENCES " + TABLE_RECIPES + "(" + RECIPE_ID + "), " +
"FOREIGN KEY (" + INGREDIENT_ID + ") REFERENCES " + TABLE_INGREDIENTS + "(" + INGREDIENT_ID + ")" +
")";
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_RECIPES);
db.execSQL(CREATE_TABLE_INGREDIENTS);
db.execSQL(CREATE_TABLE_RECIPE_INGREDIENTS);
}
Thank you for reading and I really appreciate any help i can get with this.
TABLE_INGREDIENTS is a variable. It's value is likely not "TABLE_INGREDIENTS" that is a string literal. So you might want to change
"FROM TABLE_INGREDIENTS " +
to
"FROM " + TABLE_INGREDIENTS +
(You have a number of other similar issues in your SQL too.)

android.database.sqlite.SQLiteException: near ")": syntax error (code 1): [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to create a table in DB, but I am getting SQLite exception.I have tried almost everything to fix it, but of no use.I dont know why am I getting this error. Removing comma at the end gives another exception : android.database.sqlite.SQLiteException: table products has no column named _cost (code 1):
Any suggestion is welcome.
how do I fix it ?
This is my DB handler class :
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME= "products.db";
private static final String TABLE_PRODUCTS = "products";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_PRODUCTNAME = "productname";
private static final String COLUMN_VENUE = "venue";
private static final String COLUMN_DATEOFSTART = "_dateofstart";
private static final String COLUMN_DATEOFEND = "_dateofend";
private static final String DURATION_WORKSHOP= "_duration";
private static final String COST_WORKSHOP = "_cost";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context,DATABASE_NAME, factory,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + "INTEGER, " +
COST_WORKSHOP + "INTEGER, " +
");" ;
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
public void addProduct (Products products){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME,products.get_productname());
values.put(COLUMN_VENUE,products.get_venue());
values.put(COLUMN_DATEOFSTART,products.get_dateofstart());
values.put(COLUMN_DATEOFEND,products.get_dateofend());
values.put(DURATION_WORKSHOP,products.get_duration());
values.put(COST_WORKSHOP,products.get_cost());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS,null,values);
db.close();
}
LOGCAT :
Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE products(_id INTEGER PRIMARY KEY AUTOINCREMENT, productname TEXT, venue TEXT, _dateofstart TEXT, _dateofend TEXT, _durationINTEGER, _costINTEGER, );
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1675)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1606)
at com.example.dell_1.sqlite.MyDBHandler.onCreate(MyDBHandler.java:38)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.dell_1.sqlite.MyDBHandler.addProduct(MyDBHandler.java:57)
at com.example.dell_1.sqlite.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6705)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Line 38 is db.execSQL(query); and line 57 is SQLiteDatabase db = getWritableDatabase();
change your query to this , you're missing some spaces and also you must remove the last comma from the query
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + " INTEGER, " +
COST_WORKSHOP + " INTEGER " +
");" ;
db.execSQL(query);
}
replace your query with this
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + "INTEGER, " +
COST_WORKSHOP + "INTEGER " +
");" ;
actually you are putting one extra , at the end of query.
Change your query to this
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + " INTEGER, " +
COST_WORKSHOP + " INTEGER " +
");" ;
You have formatting errors in there. An extra comma and two column names concatenated with their column types. See for e.g. how _costINTEGER should be _cost INTEGER
Change AUTOINCREMENT to AUTO_INCREMENT and remove extra ',' after column COST_WORKSHOP
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTO_INCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + " INTEGER, " +
COST_WORKSHOP + " INTEGER " +
");" ;

column '_id' does not exist, nested query's

i know that there are a lot of post about this problem, but i can't find the solutions. So i'm sorry for a duplicate.
Here is my database code:
public static final String DATABASE_NAME = "MyGames.db";
public static final String TABEL_CONSOLE = "Consol_table";
public static final String COL_CONSOLE_ID = "_id";
public static final String COL_CONSOLE_NAME = "NAME";
public static final String COL_CONSOLE_PRODUCER = "PRODUCER";
public static final String COL_CONSOLE_GENERATION = "GENERATION";
public static final String COL_CONSOLE_TYPE = "TYPE";
public static final String COL_CONSOLE_PUBLICATION = "PUBLICATION";
public static final String COL_CONSOLE_ADDED = "ADDED";
public static final String TABEL_VIDEOGAME = "Videogame_table";
public static final String COL_VIDEOGAME_ID = "_id";
public static final String COL_VIDEOGAME_NAME = "NAME";
public static final String COL_VIDEOGAME_GENRE = "GENRE";
public static final String COL_VIDEOGAME_DEVELOPER = "DEVELOPER";
public static final String COL_VIDEOGAME_PRODUCER = "PRODUCER";
public static final String COL_VIDEOGAME_PUBLICATION = "PUBLICATION";
public static final String COL_VIDEOGAME_ADDED = "ADDED";
public static final String TABEL_GENRE = "Genere_table";
public static final String COL_GENRE_ID = "_id";
public static final String COL_GENRE_NAME = "NAME";
public static final String TABEL_VIDEOGAME_PLATFORM = "Videogameplatform_table";
public static final String COL_VIDEOGAME_PLATFORM_ID = "_id";
public static final String COL_VIDEOGAME_PLATFORM_VIDEOGAME_ID = "VIDEOGAME_id";
public static final String COL_VIDEOGAME_PLATFORM_CONSOLE_ID = "CONSOLE_id";
public DataBase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
createConsoleTable(db);
createVideoGameTable(db);
createGenreTable(db);
createVideoGamePlatformTable(db);
}
private void createVideoGamePlatformTable(SQLiteDatabase db) {
db.execSQL("create table " + TABEL_VIDEOGAME_PLATFORM + "(" +
COL_VIDEOGAME_PLATFORM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_VIDEOGAME_PLATFORM_VIDEOGAME_ID + " INTEGER NOT NULL," +
COL_VIDEOGAME_PLATFORM_CONSOLE_ID + " INTEGER NOT NULL," +
"FOREIGN KEY( " + COL_VIDEOGAME_PLATFORM_VIDEOGAME_ID + " ) REFERENCES " + TABEL_VIDEOGAME + " (" + COL_VIDEOGAME_ID + " )" +
"FOREIGN KEY( " + COL_VIDEOGAME_PLATFORM_CONSOLE_ID + " ) REFERENCES " + TABEL_CONSOLE + " (" + COL_CONSOLE_ID + " )" +
");");
db.execSQL("INSERT INTO " + TABEL_VIDEOGAME_PLATFORM + "(" +
COL_VIDEOGAME_PLATFORM_VIDEOGAME_ID + "," +
COL_VIDEOGAME_PLATFORM_CONSOLE_ID + ")" +
"VALUES " +
"('0', '0')," +
"('0', '2')," +
"('0', '7')," +
"('1', '0')," +
"('1', '2')," +
"('1', '7')," +
"('2', '2')," +
"('3', '6')," +
"('4', '9')," +
"('5', '0')," +
"('5', '2')," +
"('5', '7');"
);
}
private void createGenreTable(SQLiteDatabase db) {
db.execSQL("create table " + TABEL_GENRE + "(" +
COL_GENRE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_GENRE_NAME + " TEXT(40) NOT NULL" +
");");
db.execSQL("INSERT INTO " + TABEL_GENRE + "(" +
COL_GENRE_NAME + ")" +
"VALUES " +
"('GDR'), " +
"('FPS'), " +
"('TPS'), " +
"('Platform')" +
";"
);
}
private void createVideoGameTable(SQLiteDatabase db) {
db.execSQL("create table " + TABEL_VIDEOGAME + "(" +
COL_VIDEOGAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_VIDEOGAME_NAME + " TEXT(40) NOT NULL," +
COL_VIDEOGAME_GENRE + " INTEGER," +
COL_VIDEOGAME_DEVELOPER + " TEXT(25)," +
COL_VIDEOGAME_PRODUCER + " TEXT(25)," +
COL_VIDEOGAME_PUBLICATION + " TEXT(15)," +
COL_VIDEOGAME_ADDED + " INTEGER," +
"FOREIGN KEY( " + COL_VIDEOGAME_GENRE + " ) REFERENCES " + TABEL_GENRE + " (" + COL_GENRE_ID + " )" +
");");
db.execSQL("INSERT INTO " + TABEL_VIDEOGAME + " (" +
COL_VIDEOGAME_NAME + "," +
COL_VIDEOGAME_GENRE + "," +
COL_VIDEOGAME_DEVELOPER + "," +
COL_VIDEOGAME_PRODUCER + "," +
COL_VIDEOGAME_PUBLICATION + ","+
COL_CONSOLE_ADDED + ")" +
"VALUES " +
"('Mass Effect', '0', 'BioWare', 'Eletronic Arts ','2007', '0')," +
"('Mass Effect 2', '0', 'BioWare', 'Eletronic Arts ','2011', '0')," +
"('Uncharted 3', '2', 'NaugtyDog', 'Sony ','2012', '0')," +
"('Halo 5', '1', 'Bungie', 'Microsoft','2015', '0')," +
"('Mario', '3', 'Nintendo', 'Nintendo ','2015', '0')," +
"('Mass Effect 3', '0', 'BioWare', 'Eletronic Arts ','2013', '0')" +
";"
);
}
private void createConsoleTable(SQLiteDatabase db) {
db.execSQL("create table " + TABEL_CONSOLE + "( " +
COL_CONSOLE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_CONSOLE_NAME + " TEXT(40) NOT NULL," +
COL_CONSOLE_PRODUCER + " TEX(40)," +
COL_CONSOLE_GENERATION + " TEXT(15)," +
COL_CONSOLE_TYPE + " TEXT(15)," +
COL_CONSOLE_PUBLICATION + " TEXT(15)," +
COL_CONSOLE_ADDED + " INTEGER" +
");");
db.execSQL("INSERT INTO " + TABEL_CONSOLE + " ( " +
COL_CONSOLE_NAME + "," +
COL_CONSOLE_PRODUCER + "," +
COL_CONSOLE_GENERATION + "," +
COL_CONSOLE_TYPE + "," +
COL_CONSOLE_PUBLICATION + "," +
COL_CONSOLE_ADDED + ")" +
"VALUES ('PC', ' ', ' ', ' ', ' ', '0')," + //0
"('Playstation 4', 'Sony', 'Octave', 'Home', ' ', '0')," + //1
"('Playstation 3', 'Sony', 'Seventh', 'Home', ' ', '0')," + //2
"('Playstation 2', 'Sony', 'Sixth', 'Home', ' ', '0')," + //3
"('Playstation 1', 'Sony', 'fifth', 'Home', ' ', '0')," + //4
"('Playstation Vita', 'Sony', 'Octave', 'Home', ' ', '0')," + //5
"('XboxOne', 'Microsoft', 'Octave', 'Home', ' ', '0')," + //6
"('Xbox 360', 'Microsoft', 'Seventh', 'Home', ' ', '0')," + //7
"('WiiU', 'Nintendo', 'Octave', 'Home', ' ', '0')," + //8
"('Wii', 'Nintendo', 'Seventh', 'Home', ' ', '0')," + //9
"('Playstation Portable', 'Sony', 'Seventh', 'Home', ' ', '0')" + //10
";"
);
}
Here is where call th SimpleCursorAdapter :
ListView consoleGames = (ListView) popupView.findViewById(R.id.listView_all_games);
Cursor cursor = myDb.getConsoleGames(console);
String[] fromFieldNames = new String[]{DataBase.COL_VIDEOGAME_NAME};
int[] toViewsIDs = new int[]{R.id.textViewGameName};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(popupView.getContext(), R.layout.item_all_games_list, cursor, fromFieldNames, toViewsIDs, 0);
consoleGames.setAdapter(myCursorAdapter);
And here is the query
public Cursor getConsoleGames(String console) {
SQLiteDatabase db = this.getWritableDatabase();
final String query1 = "select " + COL_CONSOLE_ID + " from " + TABEL_CONSOLE + " WHERE " + COL_CONSOLE_NAME + " like " + "'" + console + "'";
final String query2 = "select " + COL_VIDEOGAME_PLATFORM_VIDEOGAME_ID + " from " + TABEL_VIDEOGAME_PLATFORM + " WHERE " + COL_VIDEOGAME_PLATFORM_CONSOLE_ID + " = ( " + query1 + ")";
String query = "select " + COL_VIDEOGAME_NAME + " from " + TABEL_VIDEOGAME + " WHERE " + COL_VIDEOGAME_ID + " = ( " + query2 + ");" ;
Cursor res = db.rawQuery(query, null);
return res;
}
And this is the LogCat:
12-14 12:14:14.894 6607-6607/com.tutecentral.mygames E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tutecentral.mygames, PID: 6607
java.lang.IllegalArgumentException: column '_id' does not exist
at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
at android.support.v4.widget.CursorAdapter.init(CursorAdapter.java:174)
at android.support.v4.widget.CursorAdapter.<init>(CursorAdapter.java:151)
at android.support.v4.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:93)
at android.support.v4.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:89)
at com.tutecentral.mygames.MainActivity.popUpAddGameEvent(MainActivity.java:157)
at com.tutecentral.mygames.MainActivity.showPopUpAddGame(MainActivity.java:143)
at com.tutecentral.mygames.MainActivity.access$200(MainActivity.java:40)
at com.tutecentral.mygames.MainActivity$2.onClick(MainActivity.java:124)
at android.view.View.performClick(View.java:4820)
at android.view.View$PerformClick.run(View.java:20157)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5578)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
How can i fix this problem?
The issue is with your query. you are using a CursorAdapter, and it expects to find the column _id as part of the cursor you are feeding it with. Add it to your query. E.g.
String query = "select " + COL_VIDEOGAME_ID + "," + COL_VIDEOGAME_NAME + " from " + TABEL_VIDEOGAME + " WHERE " + COL_VIDEOGAME_ID + " = ( " + query2 + ");" ;

ListView not displaying all data in database

I feel like this is a bit of a noob question and I'm missing something obvious but I'm just getting used to Android programming and I have come across an issue with a SQLiteDatabase and ListView.
Earlier on today I created a ListView which displays a fixture list from a database. I got it working, saved and left it. I've come back to it and added some more fixtures into the database, however when I re-run the app only the first 4 fixtures continue to appear (the ones I created initially) when there is 18 fixtures.
Here is the FixtureDB class:
public class FixturesDB extends SQLiteOpenHelper {
//Database name
private static String dbname = "fixtureList";
//Database version
private static int version = 1;
//Primary key field
public static final String KEY_ROW_ID = "_id";
//Field which stores the fixture data
public static final String KEY_DATE = "fixture_date";
//Field which stores the fixture team
public static final String KEY_TEAM = "fixture_team";
//Field which stores the fixture competition
public static final String KEY_COMPETITION = "fixture_competition";
//Constant to store the table name
public static final String DATABASE_TABLE = "fixture_table";
//Instance variable for SQLiteDatabase
private SQLiteDatabase mDB;
//Constructor method
public FixturesDB(Context context) {
super(context, dbname, null, version);
this.mDB = getWritableDatabase();
}
/**
* This method is called providing the database does not exist
*/
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + DATABASE_TABLE + " ( " + KEY_ROW_ID + " integer primary key autoincrement , "
+ KEY_DATE + " text , " + KEY_TEAM + " text , " + KEY_COMPETITION + " text ) ";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '04/02/2015', 'Bolton', 'FA Cup' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '07/02/2015', 'Everton', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '10/02/2015', 'Tottenham', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '19/02/2015', 'Besiktas', 'Europa League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '22/02/2015', 'Southampton', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '26/02/2015', 'Besiktas', 'Europa League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '01/03/2015', 'Man City', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '04/03/2015', 'Burnley', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '16/03/2015', 'Swansea', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '22/03/2015', 'Man Utd', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '04/04/2015', 'Arsenal', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '11/04/2015', 'Newcastle', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '18/04/2015', 'Hull', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '25/04/2015', 'West Brom', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '02/05/2015', 'QPR', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '09/05/2015', 'Chelsea', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '16/05/2015', 'Crystal Palace', 'Premier League' )";
db.execSQL(sql);
sql = "insert into " + DATABASE_TABLE + " ( " + KEY_DATE + "," + KEY_TEAM + "," + KEY_COMPETITION + " ) "
+ " values ( '24/05/2015', 'Stoke', 'Premier League' )";
db.execSQL(sql);
}
/**
* Returns all the fixtures in the database
*/
public Cursor getFixtures() {
return mDB.query(DATABASE_TABLE, new String[] { KEY_ROW_ID, KEY_DATE, KEY_TEAM, KEY_COMPETITION }
, null, null, null, null, KEY_TEAM + " asc ");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + dbname);
onCreate(db);
}
}
The FixtureContentProvider class:
public class FixtureContentProvider extends ContentProvider{
public static final String PROVIDER_NAME = "com.example.project.fixture";
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/fixtures" );
private static final int fixture = 1;
private static final UriMatcher uriMatcher ;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "fixtures", fixture);
}
FixturesDB mDB;
#Override
public boolean onCreate() {
mDB = new FixturesDB(getContext());
return true;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if(uriMatcher.match(uri)==fixture){
return mDB.getFixtures();
}else{
return null;
}
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
and the Fixtures class:
public class Fixtures extends FragmentActivity implements LoaderCallbacks<Cursor> {
SimpleCursorAdapter mAdapter;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_fixtures);
listView = (ListView) findViewById(R.id.listview);
mAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.listview_fixtures_layout, null,
new String[] {FixturesDB.KEY_DATE, FixturesDB.KEY_TEAM, FixturesDB.KEY_COMPETITION},
new int[] {R.id.date, R.id.team, R.id.competition}, 0);
listView.destroyDrawingCache();
listView.setVisibility(ListView.INVISIBLE);
listView.setVisibility(ListView.VISIBLE);
listView.setAdapter(mAdapter);
/**
* This creates a loader to populate the list view from the sqlite database
*/
getSupportLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Uri uri = FixtureContentProvider.CONTENT_URI;
return new CursorLoader(this, uri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
mAdapter.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
}
I assume I have to refresh or close the database then re-open or something like that?
Thanks in advance.
Edit
I've answered my own question by simply un-installing the app and re-installing it to the device.
Noob moment.
Judging by the stub implementation of your content provider, it seems you must be assuming that if you add more insert statements to your onCreate method for your SQLiteOpenHelper that the new rows will show up in your fixtures table.
This is not the case.
The reason is that onCreate is only called once when your database is first created (no database file on the file system yet exists.)
To get around this for testing, you could delete your database file which is usually located in /data/data/your.package.name/databases and then re-run your app.
Or
Finish implementing your content provider and execute insert statements from some client code using a ContentResolver or ContentProviderClient.
Or
Use adb shell and insert rows into your database using the sqlite3 tool.

Categories