I am a beginner in SQLite and getting this exception in the highlighted line-
Caused by: android.database.sqlite.SQLiteException: no such table: VocabDatabase (code 1 SQLITE_ERROR): , while compiling: SELECT Word, Meaning FROM VocabDatabase WHERE _id = ?
My MainActivity code -
try {
**strong textCursor cursor = db.query(DatabaseHelper.DB_name, new String[]{"Word", "Meaning"},
"_id = ?", new String[]{Integer.toString(0)}, null, null, null);**
if (cursor.moveToFirst()) {
String word = cursor.getString(0);
String meaning = cursor.getString(0);
TextView tv1 = findViewById(R.id.tv1);
TextView tv2 = findViewById(R.id.tv2);
tv1.setText(word);
tv2.setText(meaning);
}
cursor.close();
db.close();
}catch(SQLException e){
Toast.makeText(this, "Can't access the database", Toast.LENGTH_SHORT).show();
}
SQLite Helper -
public void onCreate(SQLiteDatabase db)
{ db.execSQL("create table Vocabwords (_id integer primary key autoincrement, Word text, Meaning text)");
insertNewEntry(db, "Diabolic","Evil");
insertNewEntry(db,"Concede","Agree to an argument after declaring it incorrect in past");
}
VocabDatabase is a database name, but in SELECT clause, you need a table
name.
Maybe the table name is Vocabwords, please check again.
Related
I have done a lot of research and was unable to find a suitable method to delete all the tables in an SQLite database. Finally, I did a code to get all table names from the database and I tried to delete the tables using the retrieved table names one by one. It didn't work as well.
Please suggest me a method to delete all tables from the database.
This is the code that I used:
public void deleteall(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
do
{
db.delete(c.getString(0),null,null);
}while (c.moveToNext());
}
function deleteall() is called on button click whos code is given as below:
public void ButtonClick(View view)
{
String Button_text;
Button_text = ((Button) view).getText().toString();
if(Button_text.equals("Delete Database"))
{
DatabaseHelper a = new DatabaseHelper(this);
a.deleteall();
Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
}}
Use DROP TABLE:
// query to obtain the names of all tables in your database
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();
// iterate over the result set, adding every table name to a list
while (c.moveToNext()) {
tables.add(c.getString(0));
}
// call DROP TABLE on every table name
for (String table : tables) {
String dropQuery = "DROP TABLE IF EXISTS " + table;
db.execSQL(dropQuery);
}
Tim Biegeleisen's answer almost worked for me, but because I used AUTOINCREMENT primary keys in my tables, there was a table called sqlite_sequence. SQLite would crash when the routine tried to drop that table. I couldn't catch the exception either. Looking at https://www.sqlite.org/fileformat.html#internal_schema_objects, I learned that there could be several of these internal schema tables that I shouldn't drop. The documentation says that any of these tables have names beginning with sqlite_ so I wrote this method
private void dropAllUserTables(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
//noinspection TryFinallyCanBeTryWithResources not available with API < 19
try {
List<String> tables = new ArrayList<>(cursor.getCount());
while (cursor.moveToNext()) {
tables.add(cursor.getString(0));
}
for (String table : tables) {
if (table.startsWith("sqlite_")) {
continue;
}
db.execSQL("DROP TABLE IF EXISTS " + table);
Log.v(LOG_TAG, "Dropped table " + table);
}
} finally {
cursor.close();
}
}
delete database instead of deleting tables and then create new with same name if you need. use following code
context.deleteDatabase(DATABASE_NAME);
or
context.deleteDatabase(path);
For me, the working solution is:
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type IS 'table'" +
" AND name NOT IN ('sqlite_master', 'sqlite_sequence')",
null
);
if(c.moveToFirst()){
do{
db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
}while(c.moveToNext());
}
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 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);
this is my code :
SQLiteDatabase.loadLibs(this);
File databaseFile = getDatabasePath("db");
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "Ab61", null);
database.execSQL("drop table comments");
database.execSQL("CREATE TABLE IF NOT EXISTS comments(_id INTEGER PRIMARY KEY,spot_id INTEGER,server_id INTEGER" +
",description TEXT,uid TEXT ,dates TEXT,name TEXT)");
database.execSQL("insert into comments values (null, 34, 3, 'asdasd', 'asdsad', 'asda', 'asds');");
Cursor ss=db.rawQuery("SELECT * from comments", null);
Log.v("this",Integer.toString(ss.getCount()));
I've db database ,it's an sqlite database . this is a test code so , I remove the whole database ,create it again and insert a new row .
It doesn't get any error .
the cursor getCount return 0 , it means there is nothing added to database .
It driving me crazy :(
could you help me ?
You are inserting the data into a different database (database) than that which you are querying (db).
private void InitializeSQLCipher(){
try {
SQLiteDatabase.loadLibs(getApplicationContext());
}
catch (Exception e) {
e.printStackTrace();
}
File databaseFile = getDatabasePath("demo.db");
databaseFile.mkdirs();
databaseFile.delete();
database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null);
database.execSQL("create table t1(a, b)");
database.execSQL("insert into t1(a, b) values(?, ?)", new Object[]{"one for the money","two for the show"});
}
Cursor c = null;
c = database.rawQuery("SELECT a,b from t1", null);
if (c != null){
if(c.moveToFirst()){
while(!c.isAfterLast()){
//Log.e("xlcx", c.getString(c.getColumnIndex("a")));
Log.d("xlcx", c.getString(c.getColumnIndex("b")));
c.moveToNext();
}
}
}
please refer
http://androidjug.blogspot.in/2014/07/sqlcipher-for-android-application.html
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.