I am trying to insert data in my sqlit database but I got android SQLiteConstraintException: error code 19: constraint failed exception. I saw there are tons of question in this topic, I've read and tried a bunch of them, but the exception still , i wonder if this exception caused by the auto increment food_id value , since the insert statement return -1 , and i wonder that why this exception occur since the first insert id done correctly but all the later inserting are failed , why this error occur ,and how i can solve it? please help me..
the create statements in the DBAdapter class
private static final String Meal_TABLE_CREATE= "create table IF NOT EXISTS Meal (Date text not null , "+
"Time text not null,MealType text not null,"+ " primary key(Date,Time ,MealType) );" ;
private static final String FOOD_TABLE_CREATE= "create table IF NOT EXISTS Food (_id INTEGER primary key AUTOINCREMENT , "+
"Food_Name text not null,Calories integer not null,"+ "VB12 integer not null,Cholesterol integer not null,"+
"Protein integer not null,Iron integer not null,Sodium integer not null,Fat_Mono integer not null,Fat_Sat integer not null,carbohydrate integer not null);" ;
private static final String MealFOOD_TABLE_CREATE= "create table IF NOT EXISTS MealFood (Date text not null , "+
"Time text not null,MealType text not null,"+"Food_ID integer not null , primary key(Date,Time ,MealType,Food_ID) );" ;
inserting methods
// insert meal to the meal table
public long SaveMeal(String date , String time , String mealType)
{
ContentValues content = new ContentValues();
content.put(KEY_MDATE,date);
content.put(KEY_MTIME,time);
content.put(KEY_MEALTYPE,mealType);
return db.insert(MEAL_TABLE_NAME, null, content);
}
// insert Food to the Food table
public long SaveFood(String name,int calories,int Vit_B12,int cholesterol,int protein ,int iron ,int sodium,int Fat_Mono,int Fat_Sat,int carbohydrate)
{
ContentValues content = new ContentValues();
content.put(KEY_FOODNAME,name);
content.put(KEY_CALORIES,calories);
content.put(KEY_VB12,Vit_B12);
content.put(KEY_CHOLESTEROL,cholesterol);
content.put(KEY_PROTEIN,protein);
content.put(KEY_IRON,iron);
content.put(KEY_SODIUM,sodium);
content.put(KEY_FAT_MONO,Fat_Mono);
content.put(KEY_FAT_Sat,Fat_Sat);
content.put(KEY_CARBOHYDRATE,carbohydrate);
return db.insert(FOOD_TABLE_NAME, null, content);
}
// get food id by its name
public int getFoodIDByName(String name) throws SQLException
{ int id;
Cursor cursor = null;
try{
cursor=db.query(true,FOOD_TABLE_NAME, new String[]{KEY_FOODID}, KEY_FOODNAME+ " = '" + name + "'", null, null, null, null,null);
if (cursor != null) {
cursor.moveToFirst();
}
id=0;
while (cursor.moveToNext())
id=cursor.getInt(cursor.getColumnIndex(KEY_FOODID));
}
finally{
cursor.close();
cursor.deactivate();
}
return id;
}
// insert mealFood to mealFood table
public long SaveMealFood(String date , String time , String mealType, int Food_id)
{
ContentValues content = new ContentValues();
content.put(KEY_MFDATE,date);
content.put(KEY_MFTIME,time);
content.put(KEY_MFMEALTYPE,mealType);
content.put(KEY_MFFOODID,Food_id);
return db.insert(MEALFOOD_TABLE_NAME, null, content);
}
java code
DBAdapter dbAdapter=new DBAdapter(SaveMeal.this);
dbAdapter.open();
Food n;
String m;
int FoodIDByName;
for(int i = 0; i <MealActivity.array.size(); i++){
m=MealActivity.array.get(i).toString();
Log.e("tag", m);//selected food name
for (int j = 0; j < MealActivity.tempList.size(); j++){
n=MealActivity.tempList.get(j);
if(n.getFOOD_NAME().equals(m)){
//save food
long food_id = dbAdapter.SaveFood(n.getFOOD_NAME(),n.getCALORIES(),n.getFOOD_VITAMIN_B12(),n.getCHOLESTEROL(),n.getFOOD_PROTEIN(),n.getFOOD_IRON(),n.getFOOD_SODIUM(),
n.getFOOD_MONO_UNSATURATED_FAT(),n.getFOOD_SATURATED_FAT(),n.getFOOD_TOTAL_CARBOHYDRATE());
Log.e("tag", food_id+" food inserting done");
//save meal
long meal_id= dbAdapter.SaveMeal( meal_date,meal_time,Meal.MEAL_TYPE);
Log.e("tag",meal_id+" meal inserting done");
//save meal_food
FoodIDByName=dbAdapter.getFoodIDByName(n.FOOD_NAME);
Log.e("tag",FoodIDByName+" food_id");
long meal_food_id=dbAdapter.SaveMealFood(meal_date,meal_time,Meal.MEAL_TYPE,FoodIDByName);
Log.e("tag",meal_food_id+" meal_food inserting done");
dbAdapter.close();
this result of this line Log.e("tag", food_id+" food inserting done"); in my log is -1
mylog
Database(657):at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
Database(657):at android.database.sqlite.SQLiteStatement.execute (SQLiteStatement.java:55)
Database(657):at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
-1 food inserting done
18 meal inserting done
0 food_id
13 meal_food inserting done
Try to remove all (Not NULL) constraints, and save the empty food.
If it is saved properly, try to add the constraint (NOT NULL) one by one.
I think one of the values is passed as NULL.
That error.means you are.violating a constraint (obviously). Most likely leave a "not null" column null.
You could also have violated your primary key by trying to save the same combination more than once.
Related
Hi can anyone please help me with below error in android sqlite ? really appreciate!
Caused by: android.database.sqlite.SQLiteException: no such column: House (code 1): , while compiling: select * from category where category =House
below is part of my code in which I have inserted "House" in the table
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORY_TABLE = "CREATE TABLE category( " +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"category TEXT UNIQUE)";
db.execSQL(CREATE_CATEGORY_TABLE);
}
public void addCategory(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("category", name);
db.insert(CATEGORY_TABLE, // table
null, //nullColumnHack
cv); // key/value -> keys = column names/ values = column values
db.close();}
public List getCategory(){
List<String> list=new LinkedList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.rawQuery("select * from category where category =house" , null);
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
do {
String s = (cursor.getString(1));
list.add(s);
}while (cursor.moveToNext());
return list;
}
You need to wrap house with single quotes
db.rawQuery("select * from category where category = 'house'" , null);
In my case error was in trigger I wrote on table insert and update
I have the following code in a bigger project:
final class DBlifetimeStatisticsHandler{ //implements DBvalueHandler<Cyclist, Double>{
private final String TAG = getClass().getName();
private static final boolean debug = true;
private final DBminMaxAvgHandler dbMinMaxAvgHandler = new DBminMaxAvgHandler();
// table name
private static final String TABLE_LIFETIME_STATISTICS = "lifetime_statistics";
// column names
private static final String KEY_LIFETIME_STATISTICS_ID = "lifetime_statistics_id";
private static final String KEY_MIN_MAX_AVG = "min_max_avg";
// table create statement
private static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_LIFETIME_STATISTICS + "("
+ KEY_LIFETIME_STATISTICS_ID + " LONG PRIMARY KEY NOT NULL,"
+ KEY_MIN_MAX_AVG + " LONG"
+ ")";
public void onCreateTable(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIFETIME_STATISTICS);
onCreateTable(db);
}
public long addValue(SQLiteDatabase db, Statistics Statistics ) {
ContentValues values = new ContentValues();
long ID = getLatestID(db)+1;
values.put(KEY_STATISTICS_ID, ID);
... //not important to the question
}
private long getLatestID(SQLiteDatabase db){
String selectQuery = "SELECT MAX(" + KEY_STATISTICS_ID +") FROM " + TABLE_STATISTICS;
Cursor c = db.rawQuery(selectQuery, null);
c.moveToFirst();
int id = 0;
Log.e("count", String.valueOf(c.getCount()));
if (c.moveToFirst()){
...
}
return id;
}
}
After I updated the table it is created again. So when I try to add a new value I had problems cause it always jumped into the if clause because c.moveToFirst() always returned true.
So I tried to tried to check if c.getCount() would return true but sadly it does always return 1. So the question is: Why would it return 1 on an empty table? (I do use Questoid SQLite Browser and the table is really empty)
You use aggregate function MAX, so read documentation:
There are two types of simple SELECT statement - aggregate and non-aggregate queries. A simple SELECT statement is an aggregate query if it contains either a GROUP BY clause or one or more aggregate functions in the result-set.
An aggregate query without a GROUP BY clause always returns exactly one row of data, even if there are zero rows of input data.
It might be some kind of a buggy behavior when using MAX. Check this link too Android database (SQLite) returns a non-empty cursor from an empty table
this is my solution
public Boolean isNotEmpty(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_STATISTICS, null);
while (cursor.moveToNext() ) {
return true;
}
return false;
}
You are getting a result with one row in your Cursor because that is what you requested.
The result is a single column called MAX with a value that will be the max id of all the rows in your table. In your case of an empty table, this value is null.
I am using group by to resolve this. Please check my example :
SELECT COUNT(*) FROM " + TABLE_NAME + " WHERE isSynced=0 group by isSynced
I resolve this probme this way:
SELECT COUNT(*) AS numero, MAX(tagua_lagps) as tmp_max_lagps, MAX(tagua_logps) as tmp_max_logps, MIN(tagua_lagps) as tmp_min_lagps, MIN(tagua_logps) as tmp_min_logps FROM TAB_AGUA
On empty table, c.getCount(); gives 1 but values are NULL. But numero (c.getString(c.getColumnIndex("numero")) has a value of 0.
So rather than checking c.getCount() you must check the result of count(*).
I am using sqlite
i want to print the query executed in db to insert
here is my code
// for SAving Ocean/Air sales
public int saveOrder(Order odr) throws SQLException {
SQLiteDatabase db = con.getWritableDatabase();
int ordrId = 0;
ContentValues values = new ContentValues();
values.put("cr_usr", odr.getCrUsr());
values.put("cr_ts", odr.getCrTs().toString());
values.put("eat_mst_cust_id", odr.getEatMstCustId());
values.put("ordr_dt", odr.getOrdrDt().toString());
String selectQuery = "SELECT last_insert_rowid()";
try {
// Inserting Row
db.insertOrThrow("eat_ordr", null, values);---getting error here for constraint failed
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
ordrId = cursor.getInt(0);
db.close();
} finally {
db.close();
}
return ordrId;
}
I am not getting any error but row is failed to insert bcz it returns 0 for idvalue
so i want to see executed query how to get that query?
here is my table structure
CREATE TABLE "eat_ordr" ("eat_ordr_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
"eat_mst_cust_id" VARCHAR NOT NULL REFERENCES "eat_mst_cust"("eat_mst_cust_id"),
"ordr_no" VARCHAR NOT NULL UNIQUE ,
"ordr_dt" DATETIME NOT NULL ,
"ordr_stat" VARCHAR NOT NULL ,
"last_sync_ts" DATETIME,
"cr_ts" DATETIME DEFAULT CURRENT_TIMESTAMP, "md_ts" DATETIME, "cr_usr" VARCHAR, "md_usr" VARCHAR)
The insertOrThrow documentation says:
Returns
the row ID of the newly inserted row
So this can be done much easier:
ordrId = db.insertOrThrow("eat_ordr", null, values);
I have a table with 2 columns, a numeric id and unique text. Created like this:
String CREATE_MY_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FOO + " TEXT UNIQUE"
+ ")";
db.execSQL(CREATE_MY_TABLE);
I want that when I insert KEY_FOO value and it's already in the db, nothing happens. But what I get is that the id is always incremented. No new row is inserted, that's good, but the id is autoincremented.
What I'm doing to insert is as follows:
db.insertWithOnConflict(TABLE_TEST , null, values, SQLiteDatabase.CONFLICT_NONE);
I tried CONFLICT_IGNORE, CONFLICT_ABORT, CONFLICT_ROLLBACK, all the same.
The reason I need this is because other table has a foreign key on this id, thus if the id is changed, the other table points nowhere.
How I just say to let the existing entry untouched?
Try this way. In your dbhelper class write the method like following to insert.
public int insertData(String desc) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
try {
db.beginTransaction();
cv.put(KEY_FOO, desc);
db.insertOrThrow(TABLE_TEST, null, cv);
db.setTransactionSuccessful();
} catch (Exception ex) {
return 1;
} finally {
db.endTransaction();
db.close();
}
return 0;
}
Then from your actvity you call this method with the parameter value of KEY_FOO. This method will return 1 if the exception is occurs (If you try insert a unique value) and it will return 0 if the transaction is successfull.
I hope this way will help you. Let me know if any problem.
I am developing my first application which contains an SQLite database, containing table ANIMAL which has the columns _id, animal_name, animal_bio.
The user is presented with animal names in a ListView; selecting an animal will bring him/her to a page where he/she can view the animals bio.
The problem I'm having is:
When I add the bio of each animal to the DB - no errors.
However, running the app causes the ListView (previously working) to display a blank screen.
My Insertion code:
public long populateDB(){
ContentValues initialValues = new ContentValues();
long[] rowIds = new long[animalName.length];
// Populate the animal table
for(int i = 0; i < animalName.length; i++){
initialValues.put(KEY_ANIMALNAME, animalName[i]);
initialValues.put(KEY_BIOGRAPHY, bio[i]);
rowIds[i] = qmDB.insert(ANIMAL_TABLE, null, initialValues);
}
return rowIds[0];
}
And the create database statement
private static final String DATABASE_CREATE =
"create table " + ANIMAL_TABLE +
" (_id integer primary key autoincrement, " +
"animal_name text not null, " +
"biography text not null);";
I cannot see anything wrong with this code, so if anyone has any suggestions, I'd be very grateful.
EDIT: Retrieving animals code
public Cursor retrieveAnnimals(){
return qmDB.query(ANIMAL_TABLE, new String[] {
KEY_ROWID,
KEY_ANIMALNAME,
},
null,
null,
null,
null,
ORDER_BY_NAME);
}
Calling the create and insert from application, this takes place in the ListActivity, called ListAnimals:
dbm = new MyDBManager();
dbm.open();
dbm.deleteTable();
dbm.populateTable();
myCursor = dbm.retrieveAnimals();