“Table X has no column named Y” error inserting data into a SQLite database - android-sqlite

I got this error:
10-08 22:23:06.635: E/SQLiteLog(20613): (1) table mytable has no column named GPS
10-08 22:23:06.645: E/SQLiteDatabase(20613): Error inserting AppName=Ster-Kinekor GPS=false Time=22:23:6 Network=true Date=2014/10/08
10-08 22:23:06.645: E/SQLiteDatabase(20613): android.database.sqlite.SQLiteException: table mytable has no column named GPS (code 1): , while compiling: INSERT INTO mytable(AppName,GPS,Time,Network,Date) VALUES (?,?,?,?,?)
I have checked for all the normal silly mistakes people make to get this error, pretty sure I don't have a comma or spacing wrong. Please help me find the error, really appreciate any assistance
Here's the relevant code:
public static final String KEY_ROWID = "id";
public static final String KEY_AppName = "AppName";
public static final String KEY_Date = "Date";
public static final String KEY_Time = "Time";
public static final String KEY_Gps = "GPS";
public static final String KEY_Network = "Network";
...
...
...
public void onCreate(SQLiteDatabase arg0) {
try{
arg0.execSQL("create table if not exists mytable ("
+ "id integer primary key autoincrement, "
+ KEY_AppName+" text not null,"
+ KEY_Date+" text,"
+ KEY_Time+ " text,"
+ KEY_Gps+" text,"
+ KEY_Network+" text"
+");");
} catch (Exception e){
e.printStackTrace();
}
}
public void insertRecord(LocationUsageDB lb)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues initialValues = new ContentValues();//
initialValues.put(KEY_AppName, lb.AppName); //just do the same for any other columns
initialValues.put(KEY_Date, lb.Date);
initialValues.put(KEY_Time, lb.Time);
initialValues.put(KEY_Gps, lb.Gps);
initialValues.put(KEY_Network, lb.Network);
db.insert(TABLE_NAME, null, initialValues);
db.close();
}
And I send values here:
mydb.insertRecord(new LocationUsageDB(foregroundTaskAppName, date, t.hour+":"+t.minute+":"+t.second, "false", "true" ));

Related

Database update without data loss. FATAL EXCEPTION: ModernAsyncTask #1

I need to implement an update of the database lying in the assets. User data, namely, in the "favorite" record or not, should be saved.
I already asked a question and they helped me -https://stackoverflow.com/a/53827525/10261947
Everything worked in a test application. But when I transferred the code (exactly the same) to the real application, an error occurs - E/AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #1
Process: rodionova.lyubov.brodsky, PID: 4196
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:161)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:784)
Caused by: java.lang.IllegalArgumentException: the bind value at index 4 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:169)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:205)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1397)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1239)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1110)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1278)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.insertCorePoem(PoemsDbHelper.java:121)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.getNewPoems(PoemsDbHelper.java:90)
at rodionova.lyubov.brodsky.db.PoemsDbHelper.onUpgrade(PoemsDbHelper.java:41)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:197)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
at rodionova.lyubov.brodsky.db.PoemsProvider.query(PoemsProvider.java:45)
at android.content.ContentProvider.query(ContentProvider.java:1057)
If you do not perform the update, the application is working properly, so I will post only the code DbHelper
public class PoemsDbHelper extends SQLiteAssetHelper {
public static final String DB_NAME = "brodsky.db";
public static final int DBVERSION = 3;
public static final String TBLNAME = "poems_table";
public static final String COL_ID = "id";
public static final String COL_TITLE = "title";
public static final String COl_POEM = "poem";
public static final String COL_SUBJECT = "subject";
public static final String COL_YEARS = "years";
public static final String COL_FAVOURITE = "favorite";
Context mContext;
public PoemsDbHelper(Context context) {
super(context, DB_NAME, null, DBVERSION);
mContext = context;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion)
getNewPoems(mContext, db);
}
private void getNewPoems(Context context, SQLiteDatabase db) {
InputStream is;
OutputStream os;
final String tempNewDbName = "temp_brodsky.db";
int buffersize = 4096;
byte[] buffer = new byte[buffersize];
String newDBPath = mContext.getDatabasePath(tempNewDbName).getPath();
File newDBFile = new File(newDBPath);
if (newDBFile.exists()) {
newDBFile.delete();
}
File newDBFileDirectory = newDBFile.getParentFile();
if (!newDBFileDirectory.exists()) {
newDBFileDirectory.mkdirs();
}
try {
is = context.getAssets().open("databases/" + DB_NAME);
os = new FileOutputStream(newDBFile);
int bytes_read;
while ((bytes_read = is.read(buffer,0,buffersize)) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Ouch updated database not copied - processing stopped - see stack-trace above.");
}
long id = maxid(db) + 1;
SQLiteDatabase newdb = SQLiteDatabase.openDatabase(newDBFile.getPath(),null,SQLiteDatabase.OPEN_READONLY);
Cursor csr = newdb.query(TBLNAME,null,null,null,null,null,null);
long insert_result;
db.beginTransaction();
while (csr.moveToNext()) {
insert_result = insertCorePoem(
db,
id,
csr.getString(csr.getColumnIndex(COL_TITLE)),
csr.getString(csr.getColumnIndex(COl_POEM)),
csr.getString(csr.getColumnIndex(COL_SUBJECT)),
csr.getString(csr.getColumnIndex(COL_YEARS)),
csr.getString(csr.getColumnIndex(COL_FAVOURITE))
);
if (insert_result > 0) {
id++;
}
}
db.setTransactionSuccessful();
db.endTransaction();
csr.close();
newDBFile.delete();
}
public long insertCorePoem(SQLiteDatabase db, long id, String title, String poem, String subject, String years, String favourite) {
String whereclause = COL_TITLE + "=? AND " + COl_POEM + "=? AND " + COL_SUBJECT + "=? AND " + COL_YEARS + "=?";
String[] whereargs = new String[]{
title,
poem,
subject,
years
};
Cursor csr = db.query(TBLNAME,null,whereclause,whereargs,null,null,null);
boolean rowexists = (csr.getCount() > 0);
csr.close();
if (rowexists) {
Log.d("INSERTCOREPOEM","Skipping insert of row");
return -2;
}
ContentValues cv = new ContentValues();
cv.put(COL_ID,id);
cv.put(COL_TITLE,title);
cv.put(COl_POEM,poem);
cv.put(COL_SUBJECT,subject);
cv.put(COL_YEARS,years);
cv.put(COL_FAVOURITE,favourite);
Log.d("INSERTCOREPOEM","Inserting new column with id " + String.valueOf(id));
return db.insert(TBLNAME, null, cv);
}
private long maxid(SQLiteDatabase db) {
long rv = 0;
String extractcolumn = "maxid";
String[] col = new String[]{"max(" + COL_ID + ") AS " + extractcolumn};
Cursor csr = db.query(TBLNAME,col,null,null,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(extractcolumn));
}
csr.close();
return rv;
}
}
I do not understand what is wrong. Identical code works great friend application. I would be grateful for the help.
Your issue is that you likely have a value of null in the years column of a row or rows in the updated database that data is being copied from.
Although you could change the code to handle (skip insertion or use provide a year value) the end result may not be desired. So the most likely fix would be to amend the database to have valid/useful year values.

Updating single row in SQLite Android Studio

So I'm trying to update one row of my sql database with this following method
public boolean modiService(String name, String price, String updatename, String updateprice ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, updatename);
cv.put(COLUMN_RATE, updateprice);
db.update(TABLE_SERVICE, cv, COLUMN_NAME + " = ?" , new String[] {name});
return true;
}
However, whenever the function is called, it updates all the rows. I've tried to change the values within the "update" method called but I haven't been able to make it work
There is nothing intrinsically wrong with the code that you have shown. The example below, which utilises your exact code that you have shown, works.
As such your issue is either with other unprovided code or with the method you are using to determine that no data has been updated.
For this test the following was the code for the class that is subclass of SQLiteOpenHelper, in this case ServiceDBHelper.java :-
public class ServiceDBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "service.db";
public static final int DBVERSION = 1;
public static final String TABLE_SERVICE = "service";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_RATE = "rate";
public ServiceDBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_SERVICE + "(" +
COLUMN_NAME + " TEXT PRIMARY KEY, " +
COLUMN_RATE + " TEXT" +
")";
db.execSQL(crt_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertService(String name, String price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME,name);
cv.put(COLUMN_RATE,price);
return db.insert(TABLE_SERVICE,null,cv);
}
public boolean modiService(String name, String price, String updatename, String updateprice ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, updatename);
cv.put(COLUMN_RATE, updateprice);
db.update(TABLE_SERVICE, cv, COLUMN_NAME + " = ?" , new String[] {name});
return true;
}
public void logService(String description) {
String TAG = "LOGSERVICE";
Log.d(TAG,"Logging information for the Service Table for " + description);
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_SERVICE,null,null,null,null,null,null);
Log.d(TAG,"Number of rows in the " + TABLE_SERVICE + " table is " + String.valueOf(csr.getCount()));
while (csr.moveToNext()) {
Log.d(TAG,
"Column " + COLUMN_NAME + " has a value of " + csr.getString(csr.getColumnIndex(COLUMN_NAME)) +
". Column " + COLUMN_RATE + " has a value of " + csr.getString(csr.getColumnIndex(COLUMN_RATE))
);
}
csr.close();
}
}
As you can see the modiService method is as per you code.
Other code has been added to :-
Create the table (named service) when the database is created.
Insert rows into the table to add some test data.
Write to data from the table to the log.
The following is the code used in an Activity to
- insert some rows,
- display the rows
- update (modify a row)
- display the rows
The code used in MainActivity.java was :-
public class MainActivity extends AppCompatActivity {
ServiceDBHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new ServiceDBHelper(this);
mDBHlpr.insertService("Fred","125.45");
mDBHlpr.insertService("Mary","99.75");
mDBHlpr.insertService("Harry","245.34");
mDBHlpr.logService("After initial inserts");
mDBHlpr.modiService("Mary","99.75","Susan","333.33");
mDBHlpr.logService("After Updating Mary to Susan");
}
}
The relevant output in the Log was :-
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Logging information for the Service Table for After initial inserts
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Number of rows in the service table is 3
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Fred. Column rate has a value of 125.45
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Mary. Column rate has a value of 99.75
11-18 06:51:02.303 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Harry. Column rate has a value of 245.34
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Logging information for the Service Table for After Updating Mary to Susan
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Number of rows in the service table is 3
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Fred. Column rate has a value of 125.45
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Susan. Column rate has a value of 333.33
11-18 06:51:02.307 1212-1212/so53291104.so53291104 D/LOGSERVICE: Column name has a value of Harry. Column rate has a value of 245.34
As can be seen the row Mary 99.75 has been changed using the modiService method to Susan 333.33.

SQLite app won't run at all. Force close message appears

I am creating an app using SQLite.
It crashes before loading.
I fixed all viable errors and since I do not even get a log info, I am having troubles figuring out the error.
Please help.
SQLHelper
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "MediaDB";
// Media table name
private static final String TABLE_MEDIA = "media";
// Media Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TYPE = "type";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String[] COLUMNS = {KEY_ID,KEY_TYPE,KEY_TITLE,KEY_AUTHOR};
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create media table
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
// create media table
db.execSQL(CREATE_MEDIA_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older media table if existed
db.execSQL("DROP TABLE IF EXISTS media");
// create fresh media table
this.onCreate(db);
}
//ADD MEDIA
public void addMedia(Media media){
//for logging
Log.d("addMedia", media.toString());
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TYPE, media.getType()); // get title
values.put(KEY_TITLE, media.getTitle()); // get title
values.put(KEY_AUTHOR, media.getAuthor()); // get author
// insert
db.insert(TABLE_MEDIA, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// close
db.close();
}
//GET MEDIA
public Media getMedia(int id){
// get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// build query
Cursor cursor =
db.query(TABLE_MEDIA, // table
COLUMNS, // column names
" id = ?", // selections
new String[] { String.valueOf(id) }, // d. selections args
null, // group by
null, // having
null, // order by
null); // limit
// if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// build media object
Media media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
//log
Log.d("getMedia("+id+")", media.toString());
// return media
return media;
}
//GET ALL MEDIA
public List<Media> getAllMedia() {
List<Media> medias = new LinkedList<Media>();
// build the query
String query = "SELECT * FROM " + TABLE_MEDIA;
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// go over each row, build media and add it to list
Media media = null;
if (cursor.moveToFirst()) {
do {
media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
// Add media to media
medias.add(media);
} while (cursor.moveToNext());
}
Log.d("getAllMedia()", medias.toString());
// return media
return medias;
}
//UPDATE
public int updateMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("type", media.getType()); // get title
values.put("title", media.getTitle()); // get title
values.put("author", media.getAuthor()); // get author
// updating row
int i = db.update(TABLE_MEDIA, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selection args
// close
db.close();
return i;
}
//DELETE
public void deleteMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// delete
db.delete(TABLE_MEDIA, //table name
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selections args
// close
db.close();
//log
Log.d("deleteMedia", media.toString());
}
}
Media object class
public class Media {
private int id;
private String type;
private String title;
private String author;
public Media(){}
public Media(String type, String title, String author) {
super();
this.type = type;
this.title = title;
this.author = author;
}
//getters & setters
// getting ID
public int getId(){
return this.id;
}
// setting id
public void setId(int id){
this.id = id;
}
// getting type
public String getType(){
return this.type;
}
// setting title
public void setType(String type){
this.type = type;
}
// getting title
public String getTitle(){
return this.title;
}
// setting title
public void setTitle(String title){
this.title = title;
}
// getting author
public String getAuthor(){
return this.author;
}
// setting author
public void setAuthor(String author){
this.author = author;
}
#Override
public String toString() {
return "Media [id=" + id + ", type=" + type + ",title=" + title + ", author=" + author
+ "]";
}
}
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteHelper db = new MySQLiteHelper(this);
/**
* CRUD Operations
* */
// add Media
db.addMedia(new Media("Book", "Android Application Development Cookbook", "Wei Meng Lee"));
db.addMedia(new Media("Book", "Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
db.addMedia(new Media("Book", "Learn Android App Development", "Wallace Jackson"));
// get all media
List<Media> list = db.getAllMedia();
// delete one media
db.deleteMedia(list.get(0));
// get all media
db.getAllMedia();
}
}
There's an error in you table creation:
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
TYPE is not a valid SQLlite Data Type.
Please refer to this page: https://www.sqlite.org/datatype3.html
I'd write your table creation as
String CREATE_MEDIA_TABLE = "CREATE TABLE media (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TEXT, "+
"title TEXT, "+
"author TEXT)";

Error in SQLite db creation and Inserting data

When trying to create a database with a single table I encountered the following error. Not able to point the issue causing the error. Although have created the table column, still responding with no such column
Logcat data:
03-16 12:08:35.954 1249-1249/com.example.bharathduraiswamy.comboedittext E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.example.bharathduraiswamy.comboedittext/com.example.bharathduraiswamy.comboedittext.AddSupplier}: android.database.sqlite.SQLiteException: no such
column: _id (code 1): , while compiling: SELECT _id, supplier_name, supplier_contact_number, supplier_address FROM SUPPLIER
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: SELECT _id, supplier_name, supplier_contact_number,
supplier_address FROM SUPPLIER
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
at com.example.bharathduraiswamy.comboedittext.VivzDatabaseAdapter.getAllRows(VivzDatabaseAdapter.java:78)
at com.example.bharathduraiswamy.comboedittext.AddSupplier.populateListView(AddSupplier.java:271)
at com.example.bharathduraiswamy.comboedittext.AddSupplier.onCreate(AddSupplier.java:71)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
            at android.app.ActivityThread.access$600(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5336)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)
MainActivity.java data:
DBAdapter myDb;
AutoCompleteTextView customerName;
EditText customerNumber, customerAddress;
customerName = (AutoCompleteTextView) findViewById(R.id.addCustomerName);
customerNumber = (EditText) findViewById(R.id.addCustomerNumber);
customerAddress = (EditText) findViewById(R.id.addCustomerAddress);
openDB();
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void addCustomer(MenuItem item) {
if (!TextUtils.isEmpty(customerName.getText().toString()) &&
!TextUtils.isEmpty(customerNumber.getText().toString())) {
myDb.insertCustomer(
customerName.getText().toString(),
customerNumber.getText().toString(),
customerAddress.getText().toString());}
}
DbHelper data: (Edited)
package com.example.bharathduraiswamy.comboedittext;
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;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
/////////////////
//START : CUSTOMER DATA
/////////////////
// Field Names:
public static final String CUSTOMER_ROWID = "customer_id";
public static final String CUSTOMER_NAME = "customer_name";
public static final String CUSTOMER_CONTACT_NUMBER = "customer_contact_number";
public static final String CUSTOMER_CONTACT_ADDRESS = "customer_contact_address";
public static final String[] CUSTOMER_KEYS = new String[] {CUSTOMER_ROWID, CUSTOMER_NAME, CUSTOMER_CONTACT_NUMBER, CUSTOMER_CONTACT_ADDRESS};
// Column Numbers for each Field Name:
public static final int COL_CUSTOMER_ROWID = 0;
public static final int COL_CUSTOMER_NAME = 1;
public static final int COL_CUSTOMER_CONTACT_NUMBER = 2;
public static final int COL_CUSTOMER_CONTACT_ADDRESS = 3;
// DataBase info:
public static final String DATABASE_NAME = "dbLeder";
public static final String CUSTOMER_TABLE = "CUSTOMERLIST";
public static final int DATABASE_VERSION = 3; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + CUSTOMER_TABLE
+ " ("
+ CUSTOMER_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CUSTOMER_NAME + " VARCHAR(255), "
+ CUSTOMER_CONTACT_NUMBER + " VARCHAR(255), "
+ CUSTOMER_CONTACT_ADDRESS + " VARCHAR(255));";
public final Context context;
public DatabaseHelper myDBHelper;
public SQLiteDatabase db;
/////////////////
//END : CUSTOMER DATA
/////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
//onClick Method for Check - addCustomer
public long insertCustomer(String custName, String custContactNumber, String custContactAddress) {
ContentValues initialValues = new ContentValues();
initialValues.put(CUSTOMER_NAME, custName);
initialValues.put(CUSTOMER_CONTACT_NUMBER, custContactNumber);
initialValues.put(CUSTOMER_CONTACT_ADDRESS, custContactAddress);
// Insert the data into the database.
return db.insert(CUSTOMER_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = CUSTOMER_ROWID + "=" + rowId;
return db.delete(CUSTOMER_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(CUSTOMER_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, CUSTOMER_TABLE, CUSTOMER_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = CUSTOMER_ROWID + "=" + rowId;
Cursor c = db.query(true, CUSTOMER_TABLE, CUSTOMER_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String custName, String custContactNumber, String custContactAddress) {
String where = CUSTOMER_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(CUSTOMER_NAME, custName);
newValues.put(CUSTOMER_CONTACT_NUMBER, custContactNumber);
newValues.put(CUSTOMER_CONTACT_ADDRESS, custContactAddress);
// Insert it into the database.
return db.update(CUSTOMER_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS" + CUSTOMER_TABLE);
onCreate(_db); // Recreates the onCreate()
}
}
}
Nothing strikes me as wrong in your code.
Did you increment the DATABASE_VERSION field to make sure your onUpgradee() method is called ?
If you did that already, maybe try to uninstall the app from your device. That will erase the existing database. If this work, that would probably mean that your onUpgrade() method does not work.
Good luck.
EDIT : Check your onUpgrade() method. You don't have a space after "EXISTS". You need one otherwise the query won't work.
The new Logcat shows that you are having a different error. I think what it tells you is that you should have at least one column called "_id" in your table.
This is sort of a must have when working in SQLite on Android because some of the convenience methods look for this column name.
If you search StackOverflow, you will find some answers tell you that you can Alias this row and don't have to change the design of your table, but I'd say go ahead and change your design.

SQLiteException no such table

just starting out on Android and I am trying to create a simple app that has an SQLite database for collecting names and contact nos. I created a view activity that will display the contents in a list view using a simpleCursorAdapter (yes its depreciated but I have yet to cover using custom adapters. Anyway, so far the code compiles just fine. Its when I click on the button to start the view activity I get an
SQLite exception: no such table: clientTable (code 1): , while compiling: SELECT _id, name, mobile FROM clientTable.
below is the code for my database class
package com.example.ideahutquizz;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ClientDatabase extends SQLiteOpenHelper {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_MOBILE = "mobile";
public static final String DATABASE_NAME = "clientDatabase";
public static final String TABLE_NAME = "clientTable";
public static final int DATABASE_VERSION = 1;
String CREATE_TABLE = "create table"
+ TABLE_NAME + "("
+ KEY_ROWID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + "TEXT NOT NULL,"
+ KEY_MOBILE + "TEXT NOT NULL" + ")";
public ClientDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
and here is the code for the view activity
package com.example.ideahutquizz;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ViewDataActivity extends ActionBarActivity {
Button back;
ListView clientList;
SQLController clientDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
clientList = (ListView)findViewById(R.id.listView1);
back = (Button)findViewById(R.id.button1);
clientDB = new SQLController(this);
clientDB.open();
Cursor cursor = clientDB.readData();
String[] from = new String[]{ClientDatabase.KEY_ROWID, ClientDatabase.KEY_NAME, ClientDatabase.KEY_MOBILE};
int[] to = new int[]{R.id.textView_id, R.id.textView_name, R.id.textView_mobile};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_item_row, cursor, from, to);
adapter.notifyDataSetChanged();
clientList.setAdapter(adapter);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
clientDB.close();
Intent back = new Intent(ViewDataActivity.this, ControlPanel.class);
startActivity(back);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_data, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
any help is much appreciated.
updated....
I altered the create table statement as follows but I am still getting the same error...
private static final String CREATE_TABLE =
"create table " + TABLE_NAME + "("
+ KEY_ROWID + " integer primary key autoincrement,"
+ KEY_NAME + " text not null,"
+ KEY_MOBILE + " text not null" + ")";
The table isn't created:
String CREATE_TABLE = "create table"
+ TABLE_NAME + "("
Will produce this string:
String CREATE_TABLE = "create tableclientTable("
You need to add a space after the create table:
String CREATE_TABLE = "create table "
+ TABLE_NAME + "("
Same goes for the field names
So, at the end, the string will be:
String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_MOBILE + " TEXT NOT NULL" + ")";
Your CREATE TABLE statement will fail due to some missing spaces;
String CREATE_TABLE = "create table"
+ TABLE_NAME + "("
+ KEY_ROWID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + "TEXT NOT NULL,"
+ KEY_MOBILE + "TEXT NOT NULL" + ")";
...will result in something like
create tableclientTable(
_idINTEGER PRIMARY KEY AUTOINCREMENT,
nameTEXT NOT NULL,
mobileTEXT NOT NULL)
...which will cause a syntax error and not create the table.