These are the fields in table.
public static String Table_Train_Demo = "SMS_TRAIN_DEMO";
public static String Train_DEMO_ID = "TRAIN_DEMO_ID";
public static String Train_Person_Name = "PERSON_NAME";
public static String Train_Designation = "DESIGNATION";
public static String Train_Status = "STATUS";
public static String Train_Station_Or_Place_ID = "STATION_OR_PLACE_ID";
public static String Train_Discussion_ID = "DISCUSSION_ID";
public static String Train_EMP_Status_ID = "EMP_STATUS_ID";
public static String Train_Demo_Plan_ID = "DEMO_PLAN_ID";
public static String Train_APP_Plan_ID = "APP_PLAN_ID";
public static String Train_Pk = "SMS_TRAIN_DEMO_pk";
public static String Train_Constraint =
"SMS_TRAIN_DEMO_SMS_EMP_DAILY_STATUS";
public static String Train_Plan_Constraint =
"SMS_TRAIN_DEMO_SMS_PLAN_TRAIN_DEMO";
public static String Train_App_Plan_Constraint =
"SMS_TRAIN_DEMO_SMS_PLAN_APP";
This is the create statement of the table
private static final String Create_Table_Train_Demo = "CREATE TABLE " +
Table_Train_Demo + " ("
+ Train_DEMO_ID + " INTEGER NOT NULL CONSTRAINT " + Train_Pk + "
PRIMARY KEY AUTOINCREMENT, "
+ Train_Person_Name + " TEXT NOT NULL, "
+ Train_Designation + " TEXT NOT NULL, "
+ Train_Status + " INTEGER NOT NULL, "
+ Train_Station_Or_Place_ID + " INTEGER ,"
+ Train_Discussion_ID + " INTEGER NOT NULL ,"
+ Train_EMP_Status_ID + " INTEGER NOT NULL ,"
+ Train_Demo_Plan_ID + " INTEGER NOT NULL ,"
+ Train_APP_Plan_ID + " INTEGER NOT NULL ,"
+ " CONSTRAINT " + Train_Constraint + " FOREIGN KEY (" +
Train_EMP_Status_ID + ")"
+ " REFERENCES " + Table_Daily_EmpStatus + "(" + EStatus_ID + ")"
+ " CONSTRAINT " + Train_Plan_Constraint + " FOREIGN KEY (" +
Train_Demo_Plan_ID + ")"
+ " REFERENCES " + Table_Plan_Train_Demo + "(" + PTrain_Demo_Plan_ID
+ ")"
+ " CONSTRAINT " + Train_App_Plan_Constraint + " FOREIGN KEY (" +
Train_APP_Plan_ID + ")"
+ " REFERENCES " + Table_Plan_App + "(" + PAPP_Plan_ID + ")"
+ ")";
Here I am trying to insert values to the table.
public boolean addTrngDemoEntryRecord(TRN_DEMOS recInfo, long StatusEntryID,
long PID) {
SQLiteDatabase db = null;
try {
db = this.getWritableDatabase();
if (db.isOpen()) {
ContentValues values = new ContentValues();
if (recInfo != null) {
values.put(Train_Demo_Plan_ID,PID);
values.put(Train_APP_Plan_ID,PID);
values.put(Train_EMP_Status_ID,StatusEntryID);
values.put(Train_Person_Name, recInfo.PNAME);
values.put(Train_Designation, recInfo.DESG);
values.put(Train_Status, recInfo.STATUS);
values.put(Train_Discussion_ID, recInfo.DID);
values.put(Train_Station_Or_Place_ID,0);
}
long row_id = db.insert(Table_Train_Demo, null, values);
if (row_id == -1) {
return false;
} else {
return true;
}
} else
return false;
}catch (Exception e) {
Log.d("eEmp/TrngDemoplan", "Excdeption Occurred due to " +
e.toString());
return false;
} finally {
if (db != null)
db.close();
}
}
Noexceptions are coming while table creation.
But while inserting data into the table
long row_id = db.insert(Table_Train_Demo, null, values);
row_id = -1 is coming and returns false value.
what might be the problem. I am new to android.
Any help would be appreciated.
log these values recInfo.PNAME, recInfo.DESG, recInfo.STATUS and recInfo.DID
as these values can't be null.
for a try just used hardcoded values
values.put(Train_Person_Name, "xyz");
values.put(Train_Designation, "xyz");
values.put(Train_Status, "xyz");
values.put(Train_Discussion_ID,"xyz");
and check the value of row_id.
Related
I have created two tables called TermTable and CourseTable. I want CourseTable to have a foreign key to reference TermTable.
This is the code where I create the tables:
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TermDbSchema.TermTable.NAME + "(" +
"_id integer primary key autoincrement, " +
TermDbSchema.TermTable.Cols.UUID + ", " +
TermDbSchema.TermTable.Cols.TITLE + ", " +
TermDbSchema.TermTable.Cols.START_DATE + ", " +
TermDbSchema.TermTable.Cols.END_DATE +
")"
);
//I want to give CourseTable a foreign key to reference TermTable^^
db.execSQL("create table " + TermDbSchema.CourseTable.NAME + "(" +
"_id integer primary key autoincrement, " +
TermDbSchema.CourseTable.Cols.UUID + ", " +
TermDbSchema.CourseTable.Cols.TITLE + ", " +
TermDbSchema.CourseTable.Cols.START_DATE + ", " +
TermDbSchema.CourseTable.Cols.END_DATE + ", " +
TermDbSchema.CourseTable.Cols.COURSE_STATUS + ", " +
TermDbSchema.CourseTable.Cols.OPTIONAL_NOTE + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_NAME + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_PHONE + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_EMAIL +
")"
);
}
This is the code Schema code:
public class TermDbSchema {
public static final class TermTable {
public static final String NAME = "terms";
public static final class Cols {
public static final String UUID = "uuid";
public static final String TITLE = "title";
public static final String START_DATE = "startdate";
public static final String END_DATE = "enddate";
}
}
public static final class CourseTable {
public static final String NAME = "courses";
public static final class Cols {
public static final String UUID = "uuid";
public static final String TITLE = "title";
public static final String START_DATE = "startdate";
public static final String END_DATE = "enddate";
public static final String COURSE_STATUS = "coursestatus";
public static final String OPTIONAL_NOTE = "optionalnote";
public static final String MENTOR_NAME = "mentorname";
public static final String MENTOR_PHONE = "mentorphone";
public static final String MENTOR_EMAIL = "mentoremail";
}
}
How do I add a foreign key to CourseTable so that it can reference TermTable?
Change the CourseTable to have another column for the reference (link, relationship, association, mapping are all other terms) :-
public static final class CourseTable {
public static final String NAME = "courses";
public static final class Cols {
public static final String UUID = "uuid";
public static final String TITLE = "title";
public static final String START_DATE = "startdate";
public static final String END_DATE = "enddate";
public static final String COURSE_STATUS = "coursestatus";
public static final String OPTIONAL_NOTE = "optionalnote";
public static final String MENTOR_NAME = "mentorname";
public static final String MENTOR_PHONE = "mentorphone";
public static final String MENTOR_EMAIL = "mentoremail";
public static final String TERM_LINK = "termlink" //<<<<<<<<<< ADDED
}
the column name could of course be what you wish
Change the Creating SQL for the courses table to add the Foreign Key constraint.
db.execSQL("create table " + TermDbSchema.CourseTable.NAME + "(" +
"_id integer primary key autoincrement, " +
TermDbSchema.CourseTable.Cols.UUID + ", " +
TermDbSchema.CourseTable.Cols.TITLE + ", " +
TermDbSchema.CourseTable.Cols.START_DATE + ", " +
TermDbSchema.CourseTable.Cols.END_DATE + ", " +
TermDbSchema.CourseTable.Cols.COURSE_STATUS + ", " +
TermDbSchema.CourseTable.Cols.OPTIONAL_NOTE + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_NAME + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_PHONE + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_EMAIL + ", " + //<<<<<<<<<< CHANGED
TermDbSchema.CourseTable.Cols.TERM_LINK + " INTEGER REFERENCES " + TermDbSchema.TermTable.NAME + "(_id)" + //<<<<<<<<<< ADDED
")"
);
you may wish to adhere to your convetions an omit INTEGER (the type affinity of the column), that would not be an issue. It has been included because most would specifiy column types rather than have the default (NUMERIC) applied.
Important
Then override the onConfigure to call the setForeignKeyConstraintsEnabled passing true.
e.g. :-
#Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
By default Foreign Key Support is turned off, making the above coding changes will be useless unless Foreign Key Support is turned on.
You will need to then do 1 of the following :-
Delete the App's data
Uninstall the App
and then rerun the App.
Note any existing data will be lost. If you need to retain data then that could be relatively complicated.
Foreign Keys
Note that defining a foreign key is ONLY defining a constraint (rule) that requires the value being placed into the column that has the constraint to be a value in one of the rows of the parent table/column that is referenced.
Defining a Foreign Key constraint DOES NOT automatically make relationships happen. That is you will still have to determine the related term when adding a course (a common misconception is that it does this).
You may wish to consider extending the definition to include ON DELETE and ON UPDATE actions, such as CASCADE. e.g. ON DELETE CASCADE would, when a(if) term row is deleted, deleted the child rows in the course table. Likewise ON UPDATE CASCADE will update the referenced value of the children in the course table should that value be changed in the term table (these can make life simpler).
e.g. you could use :-
TermDbSchema.CourseTable.Cols.TERM_LINK + " INTEGER REFERENCES " + TermDbSchema.TermTable.NAME + "(_id) ON DELETE CASCADE ON UPDATE CASCADE" + //<<<<<<<<<< ADDED
You may wish to refer to SQLite Foreign Key Support
Define a string inside class Cols of class CourseTable which will hold the name of this new column like:
public static final String TERM_ID = "term_id";
Change the CREATE statement of the table CourseTable:
db.execSQL("create table " + TermDbSchema.CourseTable.NAME + "(" +
"_id integer primary key autoincrement, " +
TermDbSchema.CourseTable.Cols.UUID + ", " +
TermDbSchema.CourseTable.Cols.TITLE + ", " +
TermDbSchema.CourseTable.Cols.START_DATE + ", " +
TermDbSchema.CourseTable.Cols.END_DATE + ", " +
TermDbSchema.CourseTable.Cols.COURSE_STATUS + ", " +
TermDbSchema.CourseTable.Cols.OPTIONAL_NOTE + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_NAME + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_PHONE + ", " +
TermDbSchema.CourseTable.Cols.MENTOR_EMAIL + ", " +
TermDbSchema.CourseTable.Cols.TERM_ID + " INTEGER, " +
"FOREIGN KEY (" + TermDbSchema.CourseTable.Cols.TERM_ID +
") REFERENCES " + TermDbSchema.TermTable.NAME + "(_id)" +
")"
);
This new column will reference the column _id which is the PRIMARY KEY of TermTable.
You need to uninstall the app from the device so the database is deleted and then rerun to recreate the database.
Im unable to create SQLite table.
Android Studio IDE shows me error on this line "Column constrains or Comma expected, got Text"
String CREATE_TABLE_CONTACTS = "CREATE TABLE " + Util.TABLE_NAME + "(" +
Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT," +
Util.KEY_PHONE_NUMBER + " TEXT" + ")";
IMO your code
String CREATE_TABLE_CONTACTS = "CREATE TABLE " + Util.TABLE_NAME + "(" +
Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT," +
Util.KEY_PHONE_NUMBER + " TEXT" + ")";
is ok problems belongs from Util.TABLE_NAME or Util.KEY_ID check here these key strings not having spaces
DO => user_name
DON'T => user name
If your columns happen to have whitespace or other reserved words, then you may try escaping them using double quotes:
String CREATE_TABLE_CONTACTS = "CREATE TABLE \"" + Util.TABLE_NAME + "\" (" +
"\"" + Util.KEY_ID + "\" INTEGER PRIMARY KEY, \"" + Util.KEY_NAME + "\" TEXT, \"" +
Util.KEY_PHONE_NUMBER + "\" TEXT" + ")";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "addToCart_db";
public static final String TABLE_NAME = "addToCart";
public static final String COLUMN_ID = "id";
public static final String COLUMN_PRODUCT_ID = "product_id";
public static final String COLUMN_QTY = "qty";
public static final String COLUMN_PRICE = "price";
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PRODUCT_ID + " TEXT,"
+ COLUMN_PRICE + " TEXT,"
+COLUMN_QTY +" TEXT)";
try it, this formatting create table
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.)
When I try to submit data into the database, the app crashes.
Here are the parts of the java file concerned with creating and inserting data into the database.
My Contract.java class has the following information:
public class Contract {
public static abstract class customReminder{
public static final String TABLE_NAME = "CUSTOM_REMINDER";
public static final String ID = "ID";
public static final String TITLE = "TITLE";
public static final String DESCRIPTION = "DESCRIPTION";
public static final String DATE_TIME = "DATE_TIME";
public static final String[] REMINDER_COLUMNS = {ID, TITLE, DESCRIPTION, DATE_TIME};
}
My DBHelper.java class:
//SQLite statement for custom reminder table
public static final String CUSTOM_REMINDER_TABLE = "CREATE TABLE " + Contract.customReminder.TABLE_NAME + "("
+ Contract.customReminder.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Contract.customReminder.TITLE + " TEXT,"
+ Contract.customReminder.DESCRIPTION + " TEXT,"
+ Contract.customReminder.DATE_TIME + " TEXT,"
+ ");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CUSTOM_REMINDER_TABLE);
}
My CustumRemider.java class:
public boolean createCustomReminder(String title, String description, String dateTime){
ContentValues contentValues = new ContentValues();
contentValues.put(mAllColumns[1], title);
contentValues.put(mAllColumns[2], description);
contentValues.put(mAllColumns[3], dateTime);
long result = mDatabase.insert(Contract.customReminder.TABLE_NAME, null, contentValues);
return result != -1;
}
I downloaded the database to my PC from Android Device Monitor and opened it with SQLiteBrowser. I notice that a table android_metadata is created instead of CUSTOM_REMINDER.
CREATE TABLE android_metadata (locale TEXT)
I neither know where the query comes from nor why it does this.
You need to change
delete comma (",") after last parameter in create table query
public static final String CUSTOM_REMINDER_TABLE = "CREATE TABLE " + Contract.customReminder.TABLE_NAME + "("
+ Contract.customReminder.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Contract.customReminder.TITLE + " TEXT,"
+ Contract.customReminder.DESCRIPTION + " TEXT,"
+ Contract.customReminder.DATE_TIME + " TEXT"
+ ");";
instead of this
public static final String CUSTOM_REMINDER_TABLE = "CREATE TABLE " + Contract.customReminder.TABLE_NAME + "("
+ Contract.customReminder.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Contract.customReminder.TITLE + " TEXT,"
+ Contract.customReminder.DESCRIPTION + " TEXT,"
+ Contract.customReminder.DATE_TIME + " TEXT,"
+ ");";
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')"