No such column error SQLite Android - android

I have the next code to create my db..
public class ModeloPaciente extends SQLiteOpenHelper {
//Tabla Proposicion Condicional
static final String proposicionCondicionalTabla="ProposicionCondicional";
static final String colproposicionCondicionalID="ProposicionCondicionalID";
static final String colproposicionCondicionalDescripcion="ProposicionCondicionalDescripcion";
static final String colproposicionCondicionalcuandoInferirForeign="CuandoInferir";
public ModeloPaciente(Context context) {
super(context, dbName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+proposicionCondicionalTabla+" " +
"("+colproposicionCondicionalID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
colproposicionCondicionalDescripcion+ " TEXT NOT NULL," +
colproposicionCondicionalcuandoInferirForeign+" INTEGER NOT NULL,"+
"FOREIGN KEY ("+colproposicionCondicionalcuandoInferirForeign+") REFERENCES "+cuandoInferirTabla+"
("+colcuandoInferirID+"));");
}
Later I put data inside the table like this
public boolean insertarProposicion(Proposicion proposicion) {
try {
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv= new ContentValues();
cv.put(colproposicionCondicionalDescripcion, proposicion.getProposicionCondicionalDescripcion());
cv.put(colproposicionCondicionalcuandoInferirForeign, getCuandoInferirID(proposicion.getProposicionCondicionalCuandoInferirForeign()));
db.insert(proposicionCondicionalTabla, colproposicionCondicionalID, cv);
//db.close();
return true;
} catch (Exception e) {
System.out.println(e);
return false;
}
But I get an error that said:
06-07 15:36:15.507: E/Database(257): Error inserting CuandoInferir=1 ProposicionCondicionalDescripcion=Se debe inferir acerca de los dias de marcha realizados o no
06-07 15:36:15.507: E/Database(257): android.database.sqlite.SQLiteException: no such column: CuandoInferir: , while compiling: INSERT INTO ProposicionCondicional(CuandoInferir, ProposicionCondicionalDescripcion) VALUES(?, ?);
And I check the database and it has the corresponding column "CuandoInferir"..¿What happen, I do not know? Thanks for your help

You might be working with an older version of the database. Clear your app's data and try again:
Settings --> Applications --> Manage applications --> [your app] --> Clear data

Your code seems fine, however I would check the existing database. Check the column names in the 'ProposicionCondicional' table. You can do it by opening your database in sqlite3 following these steps (obviously connect your phone to pc before doing the steps)
adb shell
cd /data/data/<your.applications.package>/databases
sqlite3 <databases_name>
.schema
See if the table really has the 'CuandoInferir' column. If not, try to recreate the table.

Related

No such table: table_image (code 1): , while compiling: SELECT image_data FROM table_image WHERE image_name= ' a '

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.

SQLite Update / Replace Table Android

I have an app that gets JSON data from a server. I then put the parsed data into the android SQLite database and use the data as needed. This all works great, however, I am unable to find a method to update the whole table.
The scenario would be that this Json Data feed gets updated every week on the server. I have two Questions:
What am I missing or what is the method for updating the SQLite table? (currently this just duplicates the data)
public void updateTable(Product product){
SQLiteDatabase db = this.getWritableDatabase();
try{
ContentValues values = new ContentValues();
values.put(KEY_TYPE_NAME, product.getmProductTypeName());
// more columns here...
db.update(TABLE_NAME, values, null,null);
db.close();
}catch(Exception e){
Log.e("error:",e + "in updateData method")
}
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
Related Code in "Main Activity":
handler = new DBHandler(this);
NetworkUtils utils = new NetworkUtils(MainActivity.this);
if (handler.getProductCount() == 0 && utils.isConnectingToInternet()) {
new JsonDataParse().execute();
}`
Related Code "DBhandler" Activity:
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_TYPE_NAME + " TEXT" + ")"
That is basically my CREATE TABLE String format. I just condensed to because it has 16 columns.
This is the code I added to only delete the stored data only if there was data:
if(handler.getProductCount() == 0) {
}else{
handler.deleteData();
}
Then I just just added the delete the method as suggested:
public void deleteData() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "1", null);
}
I'm not sure what you mean by "update the whole table". It sounds to me like you just need to delete the data in the table and then use your current method to add the new data. To delete the contents you can use:
db.delete(TABLE_NAME, "1", null);
Then call your existing method to re-populate the table from the server.
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
No it wouldn't be bad practice. That makes sense, as you'll only be able to reach the server if you're connected to the internet anyway.

Android cannot insert into SQLite3 DB

I am trying to insert some data into and SQLite DB on android, but the code below just does not work. Can anyone spot the issue.
db = this.openOrCreateDatabase("data_7.db", 0, null);
db.execSQL("CREATE TABLE IF NOT EXISTS 'group' (my_id TEXT NOT NULL, my_key TEXT NOT NULL)");
db.execSQL("INSERT INTO 'group' (my_id, my_key) VALUES ('abc', '123')");
db.close();
After running the code I extracted the SQLite file off the emulator and opened it using an SQLite GUI viewer, the table was created but no data was inserted.
Note:
I have searched through this site all day and could not find a
suitable answer to this issue
I would like to do this without the aid of helper methods like
.insert(). ie. I need to user pure SQL
Try out this way:
"INSERT INTO group (my_id, my_key) " + "VALUES ('" + field_one + "', '" + field_two + "')";
you have to create the table in the method onCreate() that is found on the Dababase class that you have to build like this:
public class Database extends SQLiteOpenHelper
{
public static final String DB_NAME="YourDBName";
public static final int VERSION=1;
Context context=null;
public Database(Context context)
{
super(context, DB_NAME, null, VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
try
{
String sql="CREATE TABLE group(my_id TEXT NOT NULL PRIMARY KEY, my_key TEXT NOT NULL)";
String insert="INSERT INTO group VALUES('abc','123');";
db.execSQL(sql);
db.execSQL(insert);
}
catch(Exception e)
{
Log.d("Exception", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS group");
onCreate(db);
}
}
Make sure that the old database is deleted or change the version to 2 in order to execute the query.
If you need to execute this query you need to write:
Database db=new Database();
SQLiteDatabasse read=db.getReadableDatabase();

Inserting values to SQLite table in Android

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.

SQLite Database creation for Android App

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();
}

Categories

Resources