I have built a database helper class with an open() method and extended sqlite helper with onCreate() overridden. (shown below). Despite all of this, I am getting 'SQLiteException, no such table' error. I do not understand, why is the openHelper not helping?
public void open() {
try{
db = openHelper.getWritableDatabase();
} catch (SQLiteException e) {
db = openHelper.getReadableDatabase();
}
}
//other stuff
public static final String database_create = "create table " + database_table + " (" + primary_key + " integer primary key autoincrement, "
+ company_column + " text not null, " + product_column + " text not null);";
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(database_create);
}
the following code is meant to insert an entry temporarily, because the database cannot be empty for other reasons. It seems to execute perfectly, yet the last bit of code, which comes after is what throws the error
CompanyAndProductDatabaseAdapter cpdAdapter = new CompanyAndProductDatabaseAdapter(this);
cpdAdapter.open();
errorguard = cpdAdapter.insertPair("Loading", "...");
cpdAdapter.close();
//other stuff
cpdAdapter.open();
Cursor cursor = cpdAdapter.getAllPairsCursor(); //error here
cursor.requery();
startManagingCursor(cursor);
I don't know why you implemented a open-method, also the database_create is not what it should be.
I assume the first code is part of CompanyAndProductDatabaseAdapter.
Take a look here:
Android - Sqlite database method undefined fot type
That's almost all you need to create/get a DB with inherted SQLiteOpenHelper.
Your problem is this function:
db = openHelper.getWritableDatabase();
db = openHelper.getReadableDatabase();
First: check your path/name of the database is correct. It can create a default database, an empty database ( no tables, no nothing) if the database is not found.
Second: try to open your database this way:
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); // or OPEN_READONLY, depending on situation.
Related
I'm creating an Android project and I have a "DBFunc" class that has multiple methods to handles queries called by the activities.
DBFunc.java
public int getTotalNumberOfQuestions (String table, String category) {
String selectQuery = "SELECT COUNT(*) FROM " + table + " WHERE category='" + category + "'";
// example
// SELECT COUNT(*) FROM questions WHERE category='History';
SQLiteDatabase database = this.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
int ans = -1; // returns -1 if query unsuccessful
if (c.moveToFirst()) {
ans = c.getInt(0);
}
database.close();
c.close();
return ans;
}
I'm getting an error on the cursor, saying
android.database.sqlite.SQLiteException: no such column: category (code 1): , while compiling: SELECT COUNT(*) FROM questions WHERE category='Physics'
but I do have a category column in my questions table
When running this query through sqlite3 on the command prompt, it works and returns a number (e.g 1)
Here's what the schema looks like in "DB Browser for SQLite"
I really hope there's an easy solution, because I don't understand why it wouldn't work,
Thanks
EDIT 1:
#CL asked for the code that creates the database. The database is created in sqlite3 command line and passed into the program. But the query I used was
CREATE TABLE questions (questionId INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT, option1 TEXT, option2 TEXT, option3 TEXT, option4 TEXT, category TEXT);
EDIT 2:
I did what #Uwe Partzsch sugested and used LIKE instead of ' '
String selectQuery = "SELECT * FROM " + table + " WHERE category LIKE '" + category + "'";
But now I'm getting a different error
no such table: questions
EDIT 3:
public class DBFunc extends SQLiteOpenHelper {
public static String DB_PATH ="/data/data/com.example.healyj36.quizapp/databases/";
public static String DB_NAME = "questions.db";
public static final int DB_VERSION = 1;
public static final String TB_NAME1 = "questions";
public static final String TB_NAME2 = "answers";
private SQLiteDatabase myDB;
private Context context;
public DBFunc(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
//Copy database from source code assets to device
public void copyDataBase() throws IOException {
try {
InputStream myInput = context.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
Log.e("tle99 - copyDatabase", e.getMessage());
}
}
public void createDatabase() throws IOException {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e("tle99 - create", e.getMessage());
}
}
...
This is can exists 2 possiblities:
This problem can occurred from broken SQLite schema.
Your question is not about SQL Statement problem. but many developer can think SQL Statement problem about your question.
This case can check no demaged data in your database file. Although you can not use select fields and sql where clause by field name.
As a result, you can not use database file in your android code.
Exactly solution, I recommend recreate SQLite DB file, step by step.
You must be backup before use SQLite modification tool. (SQLite Manager, Browser, others db manage tools)
This problem occurred from your persistent data.
If you use the same file name for assets or raw data when run with modified data,
you can try uninstall previous installed app for refresh.
Probably you have added the category column latter and trying to reinstall after modifications.
Either do a clear data from the Settings>app>your_app and launc
or
Uninstall the app and then install again.
Delete your app data, also you can try LIKE instead of '='.
String selectQuery = "SELECT * FROM " + table + " WHERE category LIKE '" + category + "'";
I am a bit new to SQLite so please bear with me. I am creating a table and trying to access data from it but somehow I am getting this error.
android.database.sqlite.SQLiteException: no such table: table_image (code 1): , while compiling: SELECT image_data FROM table_image WHERE image_name= ' a '
Things that I did after the error came:
1.) Uninstalled the app and installed it again.
2.) Checked for spaces in the table creation code. It looks right to me.
I am not sure why this error is appearing then. Can someone please help me.
Thanks !!
My DatabaseHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database_name";
// Table Names
public static final String DB_TABLE = "table_image";
// column names
public static final String KEY_NAME = "image_name";
public static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + " ("+
KEY_NAME + " TEXT, " +
KEY_IMAGE + " BLOB"+")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
}
Adding stuff to db in another class
// Calling addEntry
addEntry(name, img);
// Function to add entry
public void addEntry( String name, byte[] image) throws SQLiteException {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.KEY_NAME, name);
cv.put(DatabaseHelper.KEY_IMAGE, image);
database.insert(DatabaseHelper.DB_TABLE, null, cv);
}
Then I am tying to get data from it.
SQLiteDatabase db = openOrCreateDatabase(DatabaseHelper.DB_TABLE, MODE_PRIVATE, null);
String selectQuery = "SELECT image_data FROM "+DatabaseHelper.DB_TABLE+" WHERE image_name= ' "+"a"+" ' ";
Cursor cursor = db.rawQuery(selectQuery,null);
byte[] image = cursor.getBlob(1);
openOrCreateDatabase() is not using SQLiteOpenHelper where you have the table creation code.
To get a SQLiteDatabase managed by SQLiteOpenHelper, call e.g. getWritableDatabase() on your helper object.
After fixing that, uninstall the app once more to get rid of the empty database created by openOrCreateDatabase().
Have you tried uninstalling your app and running it again?
error says "no such table: table_image", this situation can occur if you test your app with a DB with lesser number of tables and introduce a table later on.
once you relaunch your app with an additional table an older version of DB is already present and onCreate of your DBHelper will not be called and the new table will not be added in your db.
uninstalling the app will clear any previous instance of DB and onCreate will be called again and you will start with a fresh tables.
I am new in android app developement. I tried to insert values to SQLite database through the below code;
public class cashbook extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"cashbookdata.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
final String Create_CashBook =
"CREATE TABLE CashData ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "Description TEXT,"
+ "Amount REAL,"
+ "Trans INTEGER,"
+ "EntryDate TEXT);";
db.execSQL(Create_CashBook);
final String Insert_Data="INSERT INTO CashData VALUES(2,'Electricity',500,1,'04/06/2011')";
db.execSQL(Insert_Data);
It shows error on emulator - The application CashBook has stopped unexpectedly.
The database and table created , but the value insertion is not working.
Please help me to resolve this issue.
Thanks.
Seems odd to be inserting a value into an automatically incrementing field.
Also, have you tried the insert() method instead of execSQL?
ContentValues insertValues = new ContentValues();
insertValues.put("Description", "Electricity");
insertValues.put("Amount", 500);
insertValues.put("Trans", 1);
insertValues.put("EntryDate", "04/06/2011");
db.insert("CashData", null, insertValues);
okk this is fully working code edit it as per your requirement
public class TestProjectActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase( "Temp.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
try {
final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain ("
+ "ID INTEGER primary key AUTOINCREMENT,"
+ "DESCRIPTION TEXT,"
+ "expirydate DATETIME,"
+ "AMOUNT TEXT,"
+ "TRNS TEXT," + "isdefault TEXT);";
db.execSQL(CREATE_TABLE_CONTAIN);
Toast.makeText(TestProjectActivity.this, "table created ", Toast.LENGTH_LONG).show();
String sql =
"INSERT or replace INTO tbl_Contain (DESCRIPTION, expirydate, AMOUNT, TRNS,isdefault) VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);
}
catch (Exception e) {
Toast.makeText(TestProjectActivity.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();
}}}
Hope this is useful for you..
do not use TEXT for date field may be that was casing problem still getting problem let me know :)Pragna
You'll find debugging errors like this a lot easier if you catch any errors thrown from the execSQL call. eg:
try
{
db.execSQL(Create_CashBook);
}
catch (Exception e)
{
Log.e("ERROR", e.toString());
}
I recommend to create a method just for inserting and than use ContentValues.
For further info https://www.tutorialspoint.com/android/android_sqlite_database.htm
public boolean insertToTable(String DESCRIPTION, String AMOUNT, String TRNS){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("this is",DESCRIPTION);
contentValues.put("5000",AMOUNT);
contentValues.put("TRAN",TRNS);
db.insert("Your table name",null,contentValues);
return true;
}
public class TestingData extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
}
}
then see this link link
okkk you have take id INTEGER PRIMARY KEY AUTOINCREMENT and still u r passing value...
that is the problem :)
for more detail
see this
still getting problem then post code and logcat
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html
I see it is an old thread but I had the same error.
I found the explanation here:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
I'm extending the SQLiteOpenHelper class to help me connect and do my database work. According to the documentation, the OnCreate method should only be called if the database has not been created. Yet, my problem is that I am getting this error when I try to execute a query to insert a record.
ERROR/Database(214): Failure 1 (table Sample already exists) on 0x218688 when preparing
'CREATE TABLE Sample (RecId INT, SampleDesc TEXT);'.
The only place this Create query is used in code is the OnCreate method which looks like this.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SAMPLE_TABLE_CREATE);
}
Note: I'm following a tutorial - the only thing I've done different is make the SQLiteDatabase object public instead of private so that I could extend this class for each entity, letting the public SQLiteDatabase object from the inherited DataHelper class do all the work
Here is the method that makes the call that fails.
//This method is in the class that extends DataHelper (See note on tutorial)
public void createSample(Sample sample)//next action form
{
String id = sample.getId();
String name = sample.getSummary();
String query = "INSERT INTO " + SAMPLE_TABLE_NAME + "( " + SAMPLE_Id + "," +
SAMPLE_NAME + ") " + " VALUES (" + id + "," + name + ")";
try{
data.rawQuery(query, null);
}
catch(SQLException e){
Log.i("Sample", "Errors: Sample LN60: " + e.getMessage());
}
}
Can someone tell me what I'm doing wrong? Or maybe a hack (i.e. check if table exists before executing create statement)
Please let me know what other code I can post to solve this...
Is it due to you've execute it your activity once and never destroy the DB after that?
And 2nd run you'd hit this error.
Database is stored in /data/data/YOUR_PACKAGE/databases/, so a workaround would be to check if the DB exists here before creating it.
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
private static String DB_NAME = "myDBName";
SQLiteDatabase checkDB = null;
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
if(checkDB){
//do nothing
}else{
//create DB
}
Code source here
The first error is quite simply because you are creating a table that already exists, so yes adding a check if the table exists prior to creating it would be good. Once an SQLite dB is created or made it will stay until someone or something deletes it, unlike the default onCreate() call which resembles re-creating or drawing your screen.
every time you call getWritableDatabase() onCreate() method is called.
I am creating my SQLite database for my App at runtime if it does not exist and insert rows if it does. Since it is supposed to be created at runtime and I have implemented it by creating a subclass of SQLiteOpenHelper and overriding the onCreate() method -
"Do I need to put anything in the /assets folder of my project?"
I am not using any Content Provider "Do I need to add any tags in the AndroidManifest.xml?"
Here is what I have done. The strings have been defined properly and I do not get any runtime exceptions.
Implementation of the SQLiteOpenHelper subclass.
public class MyDB extends SQLiteOpenHelper {
public MyDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERAUTH_TABLE_CREATE);
db.execSQL(USERPREF_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and
recreate.");
db.execSQL("DROP TABLE IF EXISTS " + USERAUTH_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + USERPREF_TABLE_NAME);
onCreate(db);
}
}
Here is where I create an instance of the MyDB subclass of the SQLiteOpenHelper.
MyDB tdb = new MyDB(Activity.this);
SQLiteDatabase db = tdb.getReadableDatabase();
Everything runs and when I go to the sqlite shell and write the following query
select * from table_name - it just tells me no such record exist. I set breakpoints and it seems after the getReadableDatabase() is called the #Override OnCreate() method is never executed which is where I execute the Create table SQLs. I have tried getWritableDatabase()
as well.
I dont understand why the tables are not being created. If anyone can help that would be awesome.
Thanks.
Query Text String#1
private static final String USERAUTH_TABLE_CREATE =
"CREATE TABLE " + USERAUTH_TABLE_NAME + " (" +
"number INTEGER NOT NULL," +
"dip TEXT NOT NULL," +
"email TEXT NOT NULL," +
"password TEXT NOT NULL," +
"flag INTEGER" + ");" ;
Query Text String #2
private static final String USERPREF_TABLE_CREATE =
"CREATE TABLE " + USERPREF_TABLE_NAME + " (" +
"tpd TEXT NOT NULL ," +
"cat TEXT NOT NULL" + ");";
If onCreate() is not being called, then the database has already been created for your app. The quickest way to solve it is to delete your project on the emulator (Settings --> Applications --> Your application), and then restart your application. Alternatively you could use ADB to just drop your database -- it's up to you. Restarting the app after dropping the database will call onCreate() because the database does not exist, and then your table creation sql will be run. onCreate() is only called if your database DOES NOT exist (so pretty much the first time you call the database in your code.
"Do I need to put anything in the /assets folder of my project?"
No
"Do I need to add any tags in the AndroidManifest.xml?"
No
Your syntax is ok ... could you paste the query you are making for creating tables ?
This might be a silly question, but have you defined the DATABASE_NAME and DATABASE_VERSION variables?
Issue resolved. Code was working all the way once again. sqlite shell was not showing me the tables and the database. When I kept my app running on the emulator and navigated to data > data > your-package-name > databases > your-database-file using DDMS the system shows me the SQLite DB was created fine. I have checked the tables are there as well.
Thank you all guys!!
This simple application will create a data base and 1 table w and at the end it will
retrieve the value which u have enetered and vl show in textBox.
SQLiteDatabase myDB= null;
String TableName="Profile";
String ShowData="";
/* This function create new database if not exists. */
try {
myDB = openOrCreateDatabase("DataBase.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "+ TableName + " (id INT(4),firstname VARCHAR,lastname VARCHAR);");
/* Insert data to a Table*/
//myDB.execSQL("INSERT INTO "+ TableName +"(id, firstname, lastname) "+ " VALUES (1, 'Pir', 'Fahim');");
Toast.makeText(this," DATA BASE HAVE BEEN CREATED ", Toast.LENGTH_SHORT).show();
/*Fetch data from database table */
Cursor c = myDB.rawQuery("SELECT* FROM " + TableName , null);
int id = c.getColumnIndex("id");
int fristName = c.getColumnIndex("firstname");
int lastName = c.getColumnIndex("lastname");
// Check result.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
int personId = c.getInt(id);
String FirstName = c.getString(fristName);
String LastName = c.getString(lastName);
ShowData =ShowData +personId+" .) " +FirstName+" "+LastName+"\n";
txt.append("********************"+"\n"+personId+"\n"+FirstName+"\n"+LastName+"\n");
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
while(c.moveToNext());
}
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(this, "Error = "+e.getMessage(), Toast.LENGTH_LONG).show();
}
finally
{
if (myDB != null)
myDB.close();
}