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.
Related
My UpdateRow function is not working. Can someone help?
public boolean UpdateRow(String date ,String timeOut) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "=" + timeOut + "WHERE " + COL_1 + "=" + date);
}
Thanks in advance.
I think the query that you have written is missing a space between WHERE clause and COL_1. The line should be written as follows.
db.execSQL("UPDATE " + TABLE_NAME
+ " SET " + COL_3 + " = " + timeOut
+ " WHERE " + COL_1 + " = " + date
);
Apostrophes around date and space between columns:
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "=" + timeOut + " WHERE " + COL_1 + "='" + date + "'");
If timeOut is TEXT then it needs apostrophes too:
db.execSQL("UPDATE " + TABLE_NAME + " SET " + COL_3 + "='" + timeOut + "' WHERE " + COL_1 + "='" + date + "'");
I had implemented code for 2 tables and was working great. but when i wrote code for upgrade, this error comes. I have checked most related posts and even fixed a little code in the OnUpgrade where db was being recursively called. but i still cant figure it out.
Database Helper Code:
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "VotingUsers.db";
public static final String TABLE_IN = "in_Users";
public static final String TABLE_OUT = "out_Users";
public static final String COLUMN1 = "ID";
public static final String COLUMN2 = "NUMBER";
public static final String COLUMN3 = "FULL_NAME";
public static final String COLUMN4 = "DISPLAY_PICTURE";
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_IN+" ( " + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN2 + " INTEGER UNIQUE, " + COLUMN3 + " TEXT, " +COLUMN4+ " TEXT );" );
db.execSQL("CREATE TABLE "+TABLE_OUT+" ( " + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN2 + " INTEGER UNIQUE, " + COLUMN3 + " TEXT, " +COLUMN4+ " TEXT );" );
}
#Override
public void onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) {
Cursor cursor = db.rawQuery("select * from " + TABLE_IN,null);
if(cursor.getCount() != 0) {
db.execSQL("ALTER TABLE " + TABLE_IN + " ADD COLUMN FULL_NAME TEXT");
while(cursor.moveToNext()) {
db.execSQL("INSERT INTO " + TABLE_IN + " ("+COLUMN3+" ) Values ('"+cursor.getString(2) + " " + cursor.getString(3) +"')");
}
cursor.close();
}
db.execSQL("CREATE TABLE TEMP_TABLE ( " + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN2 + " INTEGER UNIQUE, " + COLUMN3 + " TEXT, " +COLUMN4+ " TEXT );" );
db.execSQL("INSERT INTO TEMP_TABLE (" +COLUMN2+", "+COLUMN3+", "+COLUMN4+" ) SELECT NUMBER, FULL_NAME, DISPLAY_PICTURE FROM "+TABLE_IN+");");
db.execSQL("DROP TABLE" + TABLE_IN);
db.execSQL("CREATE TABLE "+TABLE_IN+" ( " + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN2 + " INTEGER UNIQUE, " + COLUMN3 + " TEXT, " +COLUMN4+ " TEXT );" );
db.execSQL("INSERT INTO "+TABLE_IN+ " (" +COLUMN2+", "+COLUMN3+", "+COLUMN4+" ) SELECT " +COLUMN2+", "+COLUMN3+", "+COLUMN4+" FROM TEMP_TABLE );");
db.execSQL("DROP TABLE TEMP_TABLE");
cursor = db.rawQuery("select * from " + TABLE_OUT,null);
if(cursor.getCount() != 0) {
db.execSQL("ALTER TABLE " + TABLE_OUT + " ADD COLUMN FULL_NAME TEXT");
while(cursor.moveToNext()) {
db.execSQL("INSERT INTO " + TABLE_OUT + " ("+COLUMN3+" ) Values ('"+cursor.getString(2) + " " + cursor.getString(3) +"')");
}
cursor.close();
db.execSQL("CREATE TABLE TEMP_TABLE ( " + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN2 + " INTEGER UNIQUE, " + COLUMN3 + " TEXT, " +COLUMN4+ " TEXT );" );
db.execSQL("INSERT INTO TEMP_TABLE (" +COLUMN2+", "+COLUMN3+", "+COLUMN4+" ) SELECT NUMBER, FULL_NAME, DISPLAY_PICTURE FROM "+TABLE_OUT+");");
db.execSQL("DROP TABLE" + TABLE_OUT);
db.execSQL("CREATE TABLE "+TABLE_OUT+" ( " + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN2 + " INTEGER UNIQUE, " + COLUMN3 + " TEXT, " +COLUMN4+ " TEXT );" );
db.execSQL("INSERT INTO "+TABLE_OUT+ " (" +COLUMN2+", "+COLUMN3+", "+COLUMN4+" ) SELECT " +COLUMN2+", "+COLUMN3+", "+COLUMN4+" FROM TEMP_TABLE );");
db.execSQL("DROP TABLE TEMP_TABLE");
}
}
public void insertDataInUsers(Integer number, String name, String dp) {
String ROW1 = "INSERT INTO " + TABLE_IN + " ("
+COLUMN2+", "+COLUMN3+", "+COLUMN4+" ) Values ('"+number+"', '"+name+"', '"+dp+"')";
getDb().execSQL(ROW1);
}
public void insertDataOutUsers(Integer number, String name, String dp) {
String ROW2 = "INSERT INTO " + TABLE_OUT + " ("
+COLUMN2+", "+COLUMN3+", "+COLUMN4+" ) Values ('"+number+"', '"+name+"', '"+dp+"')";
getDb().execSQL(ROW2);
}
public SQLiteDatabase getDb() {
SQLiteDatabase db = this.getWritableDatabase();
return db;
}
public Cursor ShowInUserList() {
Cursor cursor = getDb().rawQuery("select * from " + TABLE_IN,null);
return cursor;
}
public Cursor ShowOutUserList() {
Cursor cursor = getDb().rawQuery("select * from " + TABLE_OUT,null);
return cursor;
}
Its probably a small error but i have no clue.
ERROR:
Caused by: java.lang.IllegalStateException: getDatabase called recursively
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:203)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.android.voteinoutexample.DataBaseHelper.createDb(DataBaseHelper.java:108)
at com.example.android.voteinoutexample.DataBaseHelper.ShowInUserList(DataBaseHelper.java:114)
at com.example.android.voteinoutexample.DataBaseHelper.onUpgrade(DataBaseHelper.java:42)
LINE 108 is
public Cursor ShowInUserList() {
Cursor cursor = getDb().rawQuery("select * from " + TABLE_IN,null);
return cursor;
}
In my MainFragment OnCreate, i have a condition to check if table exists, then do something..
if(!InTableExists() && !OutTableExists()) {
getUsers();
}else {
Cursor cursor = dbHelper.ShowInUserList();
if(cursor.getCount() != 0) {
data.add(new Vote(Vote.HEADER_TYPE, "IN"));
while(cursor.moveToNext()) {
data.add(new Vote(Vote.ITEM_TYPE, cursor.getString(2) + " " + cursor.getString(3),cursor.getString(4)));
}
cursor.close();
}
cursor = dbHelper.ShowOutUserList();
if(cursor.getCount() != 0) {
data.add(new Vote(Vote.HEADER_TYPE, "OUT"));
while(cursor.moveToNext()) {
data.add(new Vote(Vote.ITEM_TYPE, cursor.getString(2) + " " + cursor.getString(3),cursor.getString(4)));
}
cursor.close();
Toast.makeText(getActivity(),"DATA FROM DATABASE",Toast.LENGTH_LONG).show();
}
}
So an evaluate expression on InTableExists() in the if condition also shows result illegalStateException
The CAUSE = android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: INSERT INTO TEMP_TABLE (NUMBER, FULL_NAME, DISPLAY_PICTURE ) SELECT NUMBER, FULL_NAME, DISPLAY_PICTURE FROM in_Users);
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 + ");" ;
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')"
I created a table using the SQLiteOpenHelper:
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_SWIMMERLAPS + " INT NOT NULL, " +
KEY_SPONSOR + " DEC NOT NULL );"
);
How would I multiply the values of the swimmer laps by the sponsor using an SQLiteDatbase method?
Try this:
Cursor cursor = db.rawQuery("SELECT " + KEY_SWIMMERLAPS + " * " + KEY_SPONSOR + " AS result FROM " + DATABASE_TABLE, null);
if (cursor.moveToFirst()){
Log.w("result", cursor.getDouble(0)+"");
}