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,"
+ ");";
Related
Have the following error message:
Operation failed: table medicine has no column nameed amount(code1):, while compiling: INSERT INTO medicine(name,amount,type,info,registration_no)VALUES(?,?,?,?,?)
Config file:
public class Config {
public static final String COLUMN_MEDICINE_ID = "_id";
public static final String COLUMN_MEDICINE_NAME = "name";
public static final String COLUMN_MEDICINE_PRODUCT = "registration_no";
public static final String COLUMN_MEDICINE_INFO = "info";
public static final String COLUMN_MEDICINE_TYPE = "type";
public static final String COLUMN_MEDICINE_AMOUNT = "amount";
}
Helper File:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_MEDICINE_TABLE = "CREATE TABLE " + Config.TABLE_MEDICINE + "("
+ Config.COLUMN_MEDICINE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Config.COLUMN_MEDICINE_NAME + " TEXT NOT NULL, "
+ Config.COLUMN_MEDICINE_PRODUCT + " INTEGER NOT NULL UNIQUE, "
+ Config.COLUMN_MEDICINE_INFO + " TEXT, " //nullable
+ Config.COLUMN_MEDICINE_TYPE + " TEXT " //nullable
+ Config.COLUMN_MEDICINE_AMOUNT + " INTEGER UNIQUE, "
+ ")";
Logger.d("Table create SQL: " + CREATE_MEDICINE_TABLE);
db.execSQL(CREATE_MEDICINE_TABLE);
Logger.d("DB created!");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Config.TABLE_MEDICINE);
onCreate(db);
}
You forgot a comma between type and amount columns in the create SQL. Additionally there's a stray comma after the amount column def:
+ Config.COLUMN_MEDICINE_TYPE + " TEXT " //nullable
+ Config.COLUMN_MEDICINE_AMOUNT + " INTEGER UNIQUE, "
+ ")";
After fixing the SQL there, you can uninstall your app once to retrigger onCreate().
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.
After restart application my database always empty.
What I do wrong?
Did I clean database all the time?
here is the Code for DB class..
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.sql.Date;
import java.util.ArrayList;
import galimski.igor.com.do_ing.Task;
import galimski.igor.com.do_ing.TaskPriority;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "SQLite";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "TaskDatabase";
private static final String TABLE_TASK = "Task";
private static final String COLUMN_TASK_ID ="Id";
private static final String COLUMN_TASK_SHORT ="ShortDescription";
private static final String COLUMN_TASK_FULL = "FullDescription";
private static final String COLUMN_TASK_CREATIONDATE = "CreatedDate";
private static final String COLUMN_TASK_COMPLETIONDATE = "CompletionDate";
private static final String COLUMN_TASK_PRIORITY = "Priority";
private static final String COLUMN_TASK_SHOWN= "Shown";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "MyDatabaseHelper.onCreate ... ");
// String script = "CREATE TABLE " + TABLE_NOTE + "("
// + COLUMN_NOTE_ID + " INTEGER PRIMARY KEY," + COLUMN_NOTE_TITLE + " TEXT,"
// + COLUMN_NOTE_CONTENT + " TEXT" + ")";
//String script = "CREATE TABLE `Task` ( `Id` INTEGER NOT NULL, `ShortDescription` TEXT NOT NULL, `FullDescription` TEXT, `CreatedDate` TEXT NOT NULL, `CompletionDate` TEXT NOT NULL, `Priority` TEXT NOT NULL, PRIMARY KEY(`Id`) )";
String script = "CREATE TABLE " + TABLE_TASK + "("
+ COLUMN_TASK_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_TASK_SHORT + " TEXT,"
+ COLUMN_TASK_CREATIONDATE + " TEXT,"
+ COLUMN_TASK_COMPLETIONDATE + " TEXT,"
+ COLUMN_TASK_PRIORITY + " TEXT,"
+ COLUMN_TASK_SHOWN + " TEXT" + ")";
db.execSQL(script);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "MyDatabaseHelper.onUpgrade ... ");
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASK);
onCreate(db);
}
}
// Called when the database connection is being configured.
// Configure database settings for things like foreign key support, write-ahead logging, etc.
#Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
public void AddTask(Task task) {
Log.i(TAG, "MyDatabaseHelper.addTask ... ");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TASK_SHORT, task.GetShortDescription());
values.put(COLUMN_TASK_FULL, task.GetFullDescription());
values.put(COLUMN_TASK_CREATIONDATE, task.GetCreatedDate().toString());
values.put(COLUMN_TASK_COMPLETIONDATE, task.GetCompletionDate().toString());
values.put(COLUMN_TASK_PRIORITY, task.GetCompletionDate().toString());
db.insert(TABLE_TASK, null, values);
db.close();
}
}
Please test your application on the real android device and check if the same problem persist and just restart the application don't re-run from android studio because android studio will re-install the application every time you re-run it resulting in the empty database.
1)Run the application on the device
2)Add the data into the database
3)Close the application
4)Remove it from recent apps.
5)Re-Run it from the menu not from the android studio.
The issue you have is not that the database is being deleted or emptied; it's because the insert will not insert any data as you are trying to insert using column FullDescription (as per values.put(COLUMN_TASK_FULL, task.GetFullDescription());). However, that column does not exist in the table (according to the create table SQL you have shown).
You either need to comment out or delete the line values.put(COLUMN_TASK_FULL, task.GetFullDescription());
or if you need the column then change
String script = "CREATE TABLE " + TABLE_TASK + "("
+ COLUMN_TASK_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_TASK_SHORT + " TEXT,"
+ COLUMN_TASK_CREATIONDATE + " TEXT,"
+ COLUMN_TASK_COMPLETIONDATE + " TEXT,"
+ COLUMN_TASK_PRIORITY + " TEXT,"
+ COLUMN_TASK_SHOWN + " TEXT" + ")";
to
String script = "CREATE TABLE " + TABLE_TASK + "("
+ COLUMN_TASK_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_TASK_SHORT + " TEXT,"
+ COLUMN_TASK_FULL + " TEXT,"
+ COLUMN_TASK_CREATIONDATE + " TEXT,"
+ COLUMN_TASK_COMPLETIONDATE + " TEXT,"
+ COLUMN_TASK_PRIORITY + " TEXT,"
+ COLUMN_TASK_SHOWN + " TEXT" + ")";
If you change the table's definition by adding the column you will need to rerun the App but only after doing one of the following:-
Delete the App's data
Uninstall the App
Change private static final int DATABASE_VERSION = 1; to private static final int DATABASE_VERSION = 2;
This is because the onCreate method only runs once when the database is created 1 and 2 delete the database, 3 invokes the onCreate method via the onUpgrade method
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'm still learning Android development, And i have a problem creating an sqlite database table. here is a part of my code :
`
private static final String CREATE_ADS_PICTURE = "CREATE TABLE "
+ AdsBDD.TABLE_ADS_PICTURE + "(" + AdsBDD.ID_PICS
+ " INTEGER PRIMARY KEY AUTOINCREMENT ," + AdsBDD.AD_ID
+ " INTEGER NOT NULL," + AdsBDD.PICTURE + " TEXT," + AdsBDD.FOLDER
+ " TEXT," + AdsBDD.ORDER_NO + " INTEGER NOT NULL);";
private static final String CREATE_AGENCES = "CREATE TABLE "
+ AgencesBDD.TABLE_AGENCES + "(" + AgencesBDD.ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + AgencesBDD.GROUP
+ " INTEGER," + AgencesBDD.USERNAME + " TEXT," + AgencesBDD.EMAIL
+ " TEXT," + AgencesBDD.CONTACT_NAME + " TEXT,"
+ AgencesBDD.REGISTRATION_DATE + " TEXT," + AgencesBDD.ACTIVATION
+ " TEXT," + AgencesBDD.ACTIVE + " INTEGER," + AgencesBDD.STORE
+ " INTEGER," + AgencesBDD.STORE_BANNER + " TEXT,"
+ AgencesBDD.RATING + " REAL," + AgencesBDD.LANGUAGE + " TEXT,"
+ AgencesBDD.IDENTITY + " TEXT," + AgencesBDD.ADDRESS + " TEXT,"
+ AgencesBDD.PHONE + " TEXT," + AgencesBDD.COMPANY + " TEXT,"
+ AgencesBDD.WEBPAGE + " TEXT," + AgencesBDD.CODE_POSTAL + " TEXT,"
+ AgencesBDD.JE_SUIS_UN + " TEXT," + AgencesBDD.VILLE + " TEXT,"
+ AgencesBDD.VIDEO + " TEXT);";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_ADS_PICTURE);
db.execSQL(CREATE_AGENCES);
}
public class AgencesBDD {
public static final String TABLE_AGENCES = "agences";
public static final String ID = "id";
public static final String GROUP = "group";
public static final String USERNAME = "username";
public static final String EMAIL = "email";
public static final String CONTACT_NAME = "contact_name";
public static final String REGISTRATION_DATE = "registration_date";
public static final String ACTIVATION = "activation";
public static final String ACTIVE = "active";
public static final String STORE = "store";
public static final String STORE_BANNER = "store_banner";
public static final String RATING = "rating";
public static final String LANGUAGE = "language";
public static final String IDENTITY = "identity";
public static final String ADDRESS = "address";
public static final String PHONE = "phone";
public static final String COMPANY = "company";
public static final String WEBPAGE = "webpage";
public static final String CODE_POSTAL = "code_postal";
public static final String JE_SUIS_UN = "je_suis_un";
public static final String VILLE = "ville";
public static final String VIDEO = "video";
`
So the problem is that Sqlite throws this exception for the table AGENCES, but the Table AD_PICTURE works fine:
03-08 14:36:01.892: E/AndroidRuntime(10822): FATAL EXCEPTION: main
03-08 14:36:01.892: E/AndroidRuntime(10822): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.infonetdiffusion.immohabitation/com.infonetdiffusion.immohabitation.FragmentBaseActivity}: android.database.sqlite.SQLiteException: near "group": syntax error (code 1): , while compiling: CREATE TABLE agences(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,group INTEGER,username TEXT,email TEXT,contact_name TEXT,registration_date TEXT,activation TEXT,active INTEGER,store INTEGER,store_banner TEXT,rating REAL,language TEXT,identity TEXT,address TEXT,phone TEXT,company TEXT,webpage TEXT,code_postal TEXT,je_suis_un TEXT,ville TEXT,video TEXT);
it should be easy to fix, but i can't find where i'm wrong...
any help would be apreciated!
you are using sqlite keyword as column name i.e. group sqliteKeyword which is restrict
Drop the NOT NULL for the id column.
Read here
Those two cases are not equivalent! Note that primary key in first case doesn't have NOT NULL.
CREATE TABLE agences(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,group INTEGER,username TEXT,email TEXT,contact_name TEXT,registration_date TEXT,activation TEXT,active INTEGER,store INTEGER,store_banner TEXT,rating REAL,language TEXT,identity TEXT,address TEXT,phone TEXT,company TEXT,webpage TEXT,code_postal TEXT,je_suis_un TEXT,ville TEXT,video TEXT);
group is a key word in sql, you can't use it as a column name, change group to other strings that can't be key word in sql