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);
Related
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.)
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')"
Im unsure of my problem. I am getting no such table when queriyng the second table.. these are both within the onCreate method
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_CBID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_RACE + " TEXT NOT NULL,"
+ KEY_CLASS + " TEXT NOT NULL," + KEY_DEITY
+ " TEXT NOT NULL," + KEY_GENDER + " TEXT NOT NULL,"
+ KEY_HEIGHT + " TEXT NOT NULL," + KEY_WEIGHT
+ " TEXT NOT NULL);");
db.execSQL("CREATE TABLE " + DATABASE_TABLE2 + " (" + KEY_CSID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_SKILL
+ " TEXT NOT NULL, " + KEY_CBID + " INTEGER PRIMARY KEY FOREIGN KEY);"
);
Edit: showing cvs
String skill = "blah test";
Cursor c = ourDatabase.rawQuery("SELECT " + KEY_CBID + " FROM " + DATABASE_TABLE + " order by " + KEY_CBID + " DESC limit 1", null);
if (c != null)
{
c.moveToFirst();
cbid = c.getInt(0);
}
ContentValues cv = new ContentValues();
cv.put(KEY_SKILL, skill);
cv.put(KEY_CBID, cbid);
return ourDatabase.insert(DATABASE_TABLE2, null, cv);
My select statements is:
Cursor c = ourDatabase.rawQuery("SELECT " + KEY_SKILL + ", " + KEY_NAME + ", " + KEY_CBID + " FROM " + DATABASE_TABLE + ", " + DATABASE_TABLE2 + " WHERE " + DATABASE_TABLE +"."+KEY_CBID+" = " +DATABASE_TABLE2+"."+KEY_CBID+" && " +DATABASE_TABLE+"."+KEY_NAME+" = '"+item+"'", null);
I don't believe that your second table is being created, here is how to declare a table with a foreign key:
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER,
FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);
I took these from SQLite.org.
Also foreign keys are disabled by default in SQLite, for Android use:
db.execSQL("PRAGMA FOREIGN_KEYS=ON;");
before inserting data, if you haven't already;
check you log cat to see if there is an error while creating the second table.
If there is an error from sqllite, it will be logged in logcat
When a new table is added to DB, make sure DB is upgraded
IF from your code if you are calling db.open , if the database is already created it will be open. So in this case the code to create new table will not be hit. So you have to make sure that you upgrade the database where you can delete all your existing tables and create again
#Override
public void onCreate(SQLiteDatabase db) {
createAllTables(db);
Log.v(DBTAG, "DATABASE CREATED");
// Toast.makeText(mCtx, "created", Toast.LENGTH_SHORT).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DBTAG, "Upgrading database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
dropExistingTables(db);
onCreate(db);
}
private void dropExistingTables(SQLiteDatabase db) {
for (int i = 0; i < Utils.getDropTableQueries().size(); i++) {
db.execSQL(Utils.getDropTableQueries().get(i));
}
}
Thus to conclude make sure you are creating the table, and that no error while creating.
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)+"");
}