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 + ");" ;
Related
I recently added a column to my SQLite database, since adding this column a button which I had which sets the value of one of the database columns to "1" or "0" have now started to crash my application when the button tries to use the updateData(), so I assume thats where my issue is, is in the code or the syntax of the updateData()
Error:
android.database.sqlite.SQLiteException: near "WHERE": syntax error
(code 1 SQLITE_ERROR): , while compiling: UPDATE my_manager SET
location_name = 'blarney stone' , location_county =
'Cork',location_description = 'jj',location_route =
'1',location_position = '2',location_longg = 'null',location_lat =
'null',location_url = 'JJ',location_url2 = 'jj',location_url3 = 'jj',
WHERE location_id = '1'
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
Code:
void updateData(String id, String row_id, String name, String county, String description, String
in_route, String position, String lat, String longg, String url, String url2, String url3) {
System.out.println(TABLE_NAME+"; "+row_id +"; "+ name +"; "+ county+"; "+ description+"; " + lat
+"; "+ longg+"; "+ url +"; "+ url2 +"; "+ url3 +"; ");
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("UPDATE " + "my_manager" + " SET location_name = "+"'"+ name + "' " + ", " +
"location_county = " + "'"+ county + "'"+ "," +
"location_description = " + "'"+ description + "'" + "," +
"location_route = " + "'"+ in_route + "'" + "," +
"location_position = " + "'"+ position + "'" + "," +
"location_longg = " + "'"+ longg + "'" + "," +
"location_lat = " + "'"+ lat + "'" + "," +
"location_url = " + "'"+ url + "'" + "," +
"location_url2 = " + "'"+ url2 + "'" + "," +
"location_url3 = " + "'"+ url3 + "'" + "," + " WHERE location_id = "+"'"+ row_id+"'");
Sorry my friend don't take this as a bad but how about you avoid to much unnecessary "+" if it is possible.
void updateData("UPDATE my_manager SET location_name = '"+ name + "', " +
"location_county = '"+ county + "', " +
"location_description = '"+ description + "'," +
"location_route = '"+ in_route + "', " +
"location_position = '" + position + "', " +
"location_longg = '" + longg + "'," +
"location_lat = '" + lat + "'," +
"location_url = '" + url + "', " +
"location_url2 = '"+ url2 + "', " +
"location_url3 = '"+ url3 + "' WHERE location_id = '"+ row_id+"'");
I would like to know how to query a database based on the amount of mistakes made by a waiter.
The two tables I have are
Employee
String employeeTable = "CREATE TABLE " + EMP_TABLE + " ("
+ ID_EMP + " INTEGER PRIMARY KEY, "
+ FIRST_NAME + " TEXT,"
+ LAST_NAME + " TEXT,"
+ PROFIT + " INTEGER);";
MistakeEmployee
String mistakeTable = "CREATE TABLE " + MISTAKE_TABLE + " ("
+ ID_MISTAKE + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ID_WAITER_MISTAKE + " INTEGER,"
+ ID_ORDER_MISTAKE + " INTEGER,"
+ MISTAKE_TOTAL + " INITGER,"
+ " FOREIGN KEY (" + ID_WAITER_MISTAKE + ") REFERENCES " + EMP_TABLE + "(" + ID_EMP + "), "
+ " FOREIGN KEY (" + ID_ORDER_MISTAKE + ") REFERENCES " + ORDER_TABLE + "(" + ID_ORDER + "));";
I am trying to order the list based on the Employee with the most Mistakes which would be counted in the mistakes table using the ID_WAITER_MISTAKE.
String query = SELECT * , COUNT(Mistake_TABLE.ID_Waiter) as Count
FROM EMP_TABLE
ORDER BY Count DESC
You must join the tables, group by employee and aggregate:
SELECT e.ID_EMP, e.FIRST_NAME, e.LAST_NAME,
COUNT(m.ID_MISTAKE) AS Mistake_Count
FROM employeeTable e LEFT JOIN mistakeTable m
ON m.ID_WAITER_MISTAKE = e.ID_EMP
GROUP BY e.ID_EMP, e.FIRST_NAME, e.LAST_NAME
ORDER BY Mistake_Count DESC, e.ID_EMP
and in Java code you should construct the sql string like this:
String query =
"SELECT e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + ", " +
"COUNT(m." + ID_MISTAKE + ") AS Mistake_Count " +
"FROM " + EMP_TABLE + "AS e LEFT JOIN " + MISTAKE_TABLE + " AS m " +
"ON m." + m.ID_WAITER_MISTAKE + " = e." + ID_EMP + " " +
"GROUP BY e." + ID_EMP + ", e." + FIRST_NAME + ", e." + LAST_NAME + " " +
"ORDER BY Mistake_Count DESC, e." + ID_EMP ;
I hope there are no typos.
I want to update a SQLite Database Row by using this code:
public void updateProfile(String profileName, String col3, String col4, String col5, String col6, String col7, String col8, String col9, String col10, String col11, String col12, String col13, String col14, String col15, String col16, String col17){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET "
+ COL3 + " = '" + col3
+ COL4 + " = '" + col4
+ COL5 + " = '" + col5
+ COL6 + " = '" + col6
+ COL7 + " = '" + col7
+ COL8 + " = '" + col8
+ COL9 + " = '" + col9
+ COL10 + " = '" + col10
+ COL11 + " = '" + col11
+ COL12 + " = '" + col12
+ COL13 + " = '" + col13
+ COL14 + " = '" + col14
+ COL15 + " = '" + col15
+ COL16 + " = '" + col16
+ COL17 + " = '" + col17
+ "' WHERE " + COL2 + " = '" + profileName + "'";
Log.d(TAG, "update Profile: " + profileName);
db.execSQL(query);
}
For some reason i get some errors.
You have two recurring mistakes/errors :-
you are omitting a closing single quote around the value that is being set, and
you are omitting the , (comma) between the individual set clauses.
You want :-
public int updateProfile(String profileName, String col3, String col4, String col5, String col6, String col7, String col8, String col9, String col10, String col11, String col12, String col13, String col14, String col15, String col16, String col17){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET "
+ COL3 + " = '" + col3 + "',"
+ COL4 + " = '" + col4 + "',"
+ COL5 + " = '" + col5 + "',"
+ COL6 + " = '" + col6 + "',"
+ COL7 + " = '" + col7 + "',"
+ COL8 + " = '" + col8 + "',"
+ COL9 + " = '" + col9 + "',"
+ COL10 + " = '" + col10 + "',"
+ COL11 + " = '" + col11 + "',"
+ COL12 + " = '" + col12 + "',"
+ COL13 + " = '" + col13 + "',"
+ COL14 + " = '" + col14 + "',"
+ COL15 + " = '" + col15 + "',"
+ COL16 + " = '" + col16 + "',"
+ COL17 + " = '" + col17
+ "' WHERE " + COL2 + " = '" + profileName + "'";
Log.d(TAG, "update Profile: " + profileName);
db.execSQL(query);
}
Note the above is untested but in principle is what you want.
However;
simpler and less prone to errors is to let the SQLiteDatabase update convenience method do the work of generating the SQL for you. As such I'd suggest using :-
public void updateProfile(String profileName, String col3, String col4, String col5, String col6, String col7, String col8, String col9, String col10, String col11, String col12, String col13, String col14, String col15, String col16, String col17){
ContentValues cv = new ContentValues();
cv.put(COL3,col3);
cv.put(COL4,col4);
cv.put(COL5,col5);
cv.put(COL6,col6);
cv.put(COL7,col7);
cv.put(COL8,col8);
cv.put(COL9,col9);
cv.put(COL10,col10);
cv.put(COL11,col11);
cv.put(COL12,col12);
cv.put(COL13,col13);
cv.put(COL14,col14);
cv.put(COL15,col15);
cv.put(COL16,col16);
cv.put(COL17,col17);
SQLiteDatabase db = this.getWritableDatabase();
Log.d(TAG, "update Profile: " + profileName);
return db.update(TABLE_NAME,cv,COL2 + "=?",new String[]{profileName};
}
Again this code hasn't been tested or run so it may contain some errors.
Note the link to the update method above.
Note that public int updateProfile has been used, this means that the number of rows that have been updated will be returned, which may be useful.
the COL2 + "=?", is saying to bind the parameter, that is to replace the ? with the value as per the String[].
multiple ?'s can be used for more complex situations, in which case the first ? will be replaced by the first element in the String[], the second ? will be replaced by the 2nd element in the String[] and so on.
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.
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')"