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 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 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.
I have 3 tables
Table 1 : Member - To store every information about the member,
Attribute : MemberUsername(PK), MemberPassword
Table 2 : MsGroup - To store every registered group
Attribute : GroupId(PK), GroupName, GroupDescription
Table 3 : MsGroupDetail - To store list of every username in every group
Attribute : GroupId(PK,FK), MemberUsername(PK,FK)
My Query for Creating that 3 tables :
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_MEMBER + " ("
+ MEMBER_USERNAME + " TEXT PRIMARY KEY NOT NULL, "
+ MEMBER_PASSWORD + " TEXT NOT NULL, " + MEMBER_EMAIL
+ " TEXT NOT NULL" + ");");
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_GROUP + " ("
+ GROUP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ GROUP_NAME + " TEXT NOT NULL, " + GROUP_DESCRIPTION
+ " TEXT NOT NULL);");
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_GROUP_DETAIL + " ("
+ GROUP_ID + " INTEGER PRIMARY KEY, " + MEMBER_USERNAME
+ " TEXT, FOREIGN KEY (" + MEMBER_USERNAME
+ ") REFERENCES " + MS_MEMBER + "(" + MEMBER_USERNAME
+ "), FOREIGN KEY (" + GROUP_ID + ") REFERENCES "
+ MS_GROUP + "(" + GROUP_ID + "));");
I have successfully make some code to create member, create group, but the problem is I failed to create a query to invite/add a new member to a group (Failed to insert to MsGroupDetail)
This is the syntax for adding GroupMember
public void addGroupMember(String groupId, String username) {
// TODO Auto-generated method stub
ContentValues cv2 = new ContentValues();
cv2.put(GROUP_ID, groupId);
cv2.put(MEMBER_USERNAME, username);
ourDatabase.insert(MS_GROUP_DETAIL, null, cv2);
}
And this is the syntax to see the list of my Groups
public String[] fetchGroupName(String username) {
int i = 0;
String Query = "SELECT " + GROUP_NAME + " From " + MS_GROUP
+ " a INNER JOIN " + MS_GROUP_DETAIL + " b ON a." + GROUP_ID
+ "=b." + GROUP_ID + " WHERE " + MEMBER_USERNAME + "=?";
Cursor c = ourDatabase.rawQuery(Query, new String[] { username });
String groupName[] = new String[c.getCount()];
int iGroupName = c.getColumnIndex(GROUP_NAME);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
groupName[i] = c.getString(iGroupName);
i++;
}
c.close();
return groupName;
}
Everytime I invite a new member/adding to MsGroupDetail table, I failed to insert it to MsGroupDetail and the log cat said : "SQLite Constraint Exception, primary key must be unique"
*nb : My MsGroupDetail is once again to list every member within a group,
I have tested the same concept in Sql Server Management Studio 2008 and It worked, aI dont know any better concept than what I've coded above,
Can you guys please tell me is there any solution for this?
Thank you so much..
The problem is your GROUP_ID is not unique. If you have two members in group 1, your table will have two entries --
1, Member 1
1, Member 2
By specifying "PRIMARY KEY" on GROUP_ID you are stating it will be unique. You need different primary key. In android, it is common to use "_id", something like --
db.execSQL("CREATE TABLE IF NOT EXISTS " + MS_GROUP_DETAIL + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ GROUP_ID + " INTEGER, " + MEMBER_USERNAME
+ " TEXT, FOREIGN KEY (" + MEMBER_USERNAME
+ ") REFERENCES " + MS_MEMBER + "(" + MEMBER_USERNAME
+ "), FOREIGN KEY (" + GROUP_ID + ") REFERENCES "
+ MS_GROUP + "(" + GROUP_ID + "));");
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.