I was trying to add column to a sql db that I created. this db is for learning purpes so ignore the names of the columns ..
I had many problems while trying to do so, but after a LOT of reading I saw few things :
1. I needed to change the DB version so it will start the onUpgrade method
2. I needed to add an "ALTER TABLE" command in my onUpgrade method.
after doing so, the app stopped throwing exceptions, and I thought everything is well.
the only thing is that if I try to update the table with the new column it doesn't update anything (even though for some reason it doesn't throw exception).
my main concern is if I should have added the new column commend to the onCreat or no
the onUpdate method I created was to add the KEY_KIDS column:
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) throws SQLException{
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] + " ADD COLUMN "
+ KEY_KIDS + " text not null default kids; ");
Log.w(DBHelper.class.getName(),
"Columns added!");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[0]);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[1]);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[2]);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[3]);
onCreate(db);
}
this is the table that I whanted to add a columns to, the new column is KEY_KIDS:
public static final String Table1= "CREATE TABLE " + DATABASE_TABLE[0] + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL);" ; //
Should it be like this, or witho the KEY_KIDS declaration (KEY_KIDS + " TEXT NOT..)
pleas help. I have been trying to solve my problem for days and couldn't figure it out.
this is the whole code for the sql:
package com.Dvir.newlearning1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class HotOrNot {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_AGE = "persons_age";
public static final String KEY_HOTNESS = "persons_hotness";
public static final String KEY_Hairy = "is_hairy";
public static final String KEY_KIDS = "has_kids";
private static final String DATABASE_NAME = "NewDB2";
private static final String[] DATABASE_TABLE = {"peopleTable",
"peopleTable2", "peopleTable3","peopleTable4" };
private static final int DATABASE_VERSION = 2;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper{
public static final String Table1= "CREATE TABLE " + DATABASE_TABLE[0] + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL " +
KEY_KIDS + " TEXT NOT NULL);" ;
public static final String Table2 = "CREATE TABLE " + DATABASE_TABLE[1] + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL);";
public static final String Table3= "CREATE TABLE " + DATABASE_TABLE[2] + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL);" ;
public static final String Table4= "CREATE TABLE " + DATABASE_TABLE[3] + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL);" ;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) throws SQLException{
// TODO Auto-generated method stub
db.execSQL(Table1);
db.execSQL(Table2);
db.execSQL(Table3);
db.execSQL(Table4);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) throws SQLException{
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
/*db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] + " ADD COLUMN "
+ KEY_KIDS + " text not null default kids; ");*/
Log.w(DBHelper.class.getName(),
"Columns added!");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[0]);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[1]);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[2]);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[3]);
onCreate(db);
}
}
public HotOrNot(Context c) throws SQLException{
ourContext = c;
}
public HotOrNot open(){
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long creatEntry(String name, String age, String hotness, int table, String kids)
throws SQLException {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME,name);
cv.put(KEY_AGE, age);
cv.put(KEY_HOTNESS, hotness);
cv.put(KEY_KIDS, kids);
return ourDatabase.insert(DATABASE_TABLE[table], null, cv);
}
public long creatEntry(String name, String age, String hotness,String hasKids, int table) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME,name);
cv.put(KEY_AGE, age);
cv.put(KEY_HOTNESS, hotness);
cv.put(KEY_KIDS, hotness);
return ourDatabase.insert(DATABASE_TABLE[table], null, cv);
}
public String getData(int table) {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
Cursor c;
c = ourDatabase.query(DATABASE_TABLE[table], columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iAge = c.getColumnIndex(KEY_AGE);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " +
c.getString(iAge) + " " + c.getString(iHotness) + "\n";
}
return result;
}
public String getName(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
Cursor c = ourDatabase.query(DATABASE_TABLE[0], columns, KEY_ROWID + "=" + l, null, null,null, null);
if (c !=null){
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}
public String getHotness(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
Cursor c = ourDatabase.query(DATABASE_TABLE[0], columns, KEY_ROWID + "=" + l, null, null,null, null);
if (c !=null){
c.moveToFirst();
int iHot = c.getColumnIndex(KEY_HOTNESS);
String name = c.getString(iHot);
return name;
}
return null;
}
public String getAge(long l)throws SQLException {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
Cursor c = ourDatabase.query(DATABASE_TABLE[0], columns, KEY_ROWID + "=" + l, null, null,null, null);
if (c !=null){
c.moveToFirst();
int iAge = c.getColumnIndex(KEY_AGE);
String name = c.getString(iAge);
return name;
}
return null;
}
public void updateEntry(int table, long lRow, String mHotness, String mAge,
String mName) throws SQLException {
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_NAME, mName);
cvUpdate.put(KEY_AGE, mAge);
cvUpdate.put(KEY_HOTNESS, mHotness);
ourDatabase.update(DATABASE_TABLE[table], cvUpdate, KEY_ROWID + "=" + lRow, null);
}
public void deleteEntry(long lRow1) throws SQLException{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE[0], KEY_ROWID + "=" + lRow1, null);
}
}
another thing - I have been trying to creat a multi table DB using a for loop. but, I don't know why, it doesn't let me do it. it tried doing something like:
String[] table;
for (int i = 0; i<26, i++) {
table[i] = "CREATE TABLE " + "DATABASE_TABLE[i]" +...
}
eclips keeps red flaggin the semicolon in te end of "table" with the error:
Syntax error on token ";", { expected after this token
does someone know why?
Look at this part :
public static final String Table1= "CREATE TABLE " + DATABASE_TABLE[0] + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL " +
KEY_KIDS + " TEXT NOT NULL);" ;
You forgot the comma (,) just before the KEY_KIDS part.
This onUpgrade function does three things:
It adds the kids column;
it drops all tables from the database; and
it calls onCreate, which creates all-new tables.
The purpose of the onUpgrade function is to convert the database from some old version to the new version.
Just deleting the old database and then recreating it might be a valid way to do this (if you don't care about the data), but then you would not need to bother with ALTERing things.
Drop steps 2 and 3.
The onCreate function must create a database in the latest version, so it must include all columns of that version.
edit the line
db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] + " ADD COLUMN "
+ KEY_KIDS + " text not null default kids; ");
to
db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] + " ADD COLUMN "
+ KEY_KIDS + " text not null default 'kids'; ");
notice the single quote 'kids'. if column is of type string (eg: text, varchar, char), put in quotes, unless the data type of type number
(eg: integer, decimal) no quotes needed.
Related
I am new to sqlite and i am trying to develop an application using sqlite, but I got stuck with an error
no such column: reminder.
I searched many sites but could not find out the problem. I do not know what all details I need to post. But I am getting error in my logcat like this.
Caused by: android.database.sqlite.SQLiteException: no such column: reminder (code 1): , while compiling: SELECT id, party_name, bank_name, reminder, expiry_date, reminder_date, cheque_number, amount FROM financeTBL ORDER BY idDESC
DatabaseHandler class
public class DatabaseHandler extends SQLiteOpenHelper {
private Context ctx;
public DatabaseHandler(Context context) {
super(context, Constants.DB_NAME, null, Constants.DB_VERSION);
this.ctx = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ALERT_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "("
+ Constants.KEY_ID + " INTEGER PRIMARY KEY,"
+ Constants.KEY_PARTY_NAME + "TEXT,"
+ Constants.KEY_CHEQUE_NUMBER + "TEXT"
+ Constants.KEY_AMOUNT + "TEXT"
+ Constants.KEY_EXPIRY_DATE + "LONG"
+ Constants.KEY_REMINDER_DATE + "LONG"
+ Constants.KEY_REMINDER + "Text,"
+ Constants.KEY_BANK_NAME + "TEXT);";
db.execSQL(CREATE_ALERT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_NAME);
onCreate(db);
}
public void addfinance(Finance finance) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.KEY_PARTY_NAME, finance.getPartyName());
values.put(Constants.KEY_BANK_NAME, finance.getBankName());
values.put(Constants.KEY_REMINDER, finance.getReminder());
values.put(Constants.KEY_REMINDER_DATE, finance.getReminderDate().getTime());
values.put(Constants.KEY_AMOUNT, finance.getAmount());
values.put(Constants.KEY_CHEQUE_NUMBER,finance.getChequeNumber());
values.put(Constants.KEY_EXPIRY_DATE, finance.getExpiryDate().getTime());
db.insert(Constants.TABLE_NAME, null, values);
Log.d("Saved!!", "Saved to DB");
}
public Finance getGrocery(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(Constants.TABLE_NAME, new String[] {Constants.KEY_ID,
Constants.KEY_AMOUNT,
Constants.KEY_REMINDER_DATE,
Constants.KEY_PARTY_NAME,
Constants.KEY_BANK_NAME,
Constants.KEY_REMINDER,
Constants.KEY_CHEQUE_NUMBER,
Constants.KEY_EXPIRY_DATE},
Constants.KEY_ID + "=?",
new String[] {String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Finance finance = new Finance();
finance.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.KEY_ID))));
finance.setPartyName(cursor.getString(cursor.getColumnIndex(Constants.KEY_PARTY_NAME)));
finance.setBankName(cursor.getString(cursor.getColumnIndex(Constants.KEY_BANK_NAME)));
finance.setReminder(cursor.getString(cursor.getColumnIndex(Constants.KEY_REMINDER)));
finance.setChequeNumber(cursor.getString(cursor.getColumnIndex(Constants.KEY_CHEQUE_NUMBER)));
finance.setAmount(cursor.getString(cursor.getColumnIndex(Constants.KEY_AMOUNT)));
Date date= new Date(cursor.getLong(cursor.getColumnIndex(Constants.KEY_EXPIRY_DATE)));
finance.setExpiryDate(date);
date=new Date(cursor.getLong(cursor.getColumnIndex(Constants.KEY_REMINDER_DATE)));
finance.setReminderDate(date);
return finance;
}
//Get all Groceries
public List<Finance> getAllFinanceDetails() {
SQLiteDatabase db = this.getReadableDatabase();
List<Finance> financeList = new ArrayList<>();
Cursor cursor = db.query(Constants.TABLE_NAME, new String[] {
Constants.KEY_ID,
Constants.KEY_PARTY_NAME,
Constants.KEY_BANK_NAME,
Constants.KEY_REMINDER,
Constants.KEY_EXPIRY_DATE,
Constants.KEY_REMINDER_DATE,
Constants.KEY_CHEQUE_NUMBER
,Constants.KEY_AMOUNT
}, null, null, null, null, Constants.KEY_ID + "DESC");
if (cursor.moveToFirst()) {
do {
Finance finance = new Finance();
finance.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.KEY_ID))));
finance.setPartyName(cursor.getString(cursor.getColumnIndex(Constants.KEY_PARTY_NAME)));
finance.setBankName(cursor.getString(cursor.getColumnIndex(Constants.KEY_BANK_NAME)));
finance.setReminder(cursor.getString(cursor.getColumnIndex(Constants.KEY_REMINDER)));
Date date= new Date(cursor.getLong(cursor.getColumnIndex(Constants.KEY_EXPIRY_DATE)));
finance.setExpiryDate(date);
date=new Date(cursor.getLong(cursor.getColumnIndex(Constants.KEY_REMINDER_DATE)));
finance.setReminderDate(date);
finance.setChequeNumber(cursor.getString(cursor.getColumnIndex(Constants.KEY_CHEQUE_NUMBER)));
finance.setAmount(cursor.getString(cursor.getColumnIndex(Constants.KEY_AMOUNT)));
financeList.add(finance);
}while (cursor.moveToNext());
}
return financeList;
}
Constants class
public class Constants {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "financeDB";
public static final String TABLE_NAME = "financeTBL";
public static final String KEY_ID = "id";
public static final String KEY_PARTY_NAME = "party_name";
public static final String KEY_BANK_NAME = "bank_name";
public static final String KEY_REMINDER = "reminder";
public static final String KEY_CHEQUE_NUMBER ="cheque_number";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_EXPIRY_DATE = "expiry_date";
public static final String KEY_REMINDER_DATE = "reminder_date";
}
You're missing some commas from your CREATE TABLE statement, which means they'll be seen as one column rather than separate.
String CREATE_ALERT_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "("
+ Constants.KEY_ID + " INTEGER PRIMARY KEY,"
+ Constants.KEY_PARTY_NAME + "TEXT,"
+ Constants.KEY_CHEQUE_NUMBER + "TEXT" // <-- HERE
+ Constants.KEY_AMOUNT + "TEXT" // <-- HERE
+ Constants.KEY_EXPIRY_DATE + "LONG" // <-- HERE
+ Constants.KEY_REMINDER_DATE + "LONG" // <-- HERE
+ Constants.KEY_REMINDER + "Text,"
+ Constants.KEY_BANK_NAME + "TEXT);";
You're also missing spaces before the column type, so for example the reminder column will appear as reminderText in the constructed statement. I'd recommend reformatting your CREATE TABLE statement as so:
String CREATE_ALERT_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + " ("
+ Constants.KEY_ID + " INTEGER PRIMARY KEY,"
+ Constants.KEY_PARTY_NAME + " TEXT,"
+ Constants.KEY_CHEQUE_NUMBER + " TEXT,"
+ Constants.KEY_AMOUNT + " TEXT,"
+ Constants.KEY_EXPIRY_DATE + " LONG,"
+ Constants.KEY_REMINDER_DATE + " LONG,"
+ Constants.KEY_REMINDER + " TEXT,"
+ Constants.KEY_BANK_NAME + " TEXT);";
One more space you need to add is in the ORDER BY part of this query:
Constants.KEY_ID + "DESC"
needs to be:
Constants.KEY_ID + " DESC"
In your onCreate You are forgetting commas . try this
public void onCreate(SQLiteDatabase db) {
String CREATE_ALERT_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "("
+ Constants.KEY_ID + " INTEGER PRIMARY KEY,"
+ Constants.KEY_PARTY_NAME + " TEXT,"
+ Constants.KEY_CHEQUE_NUMBER + " TEXT,"
+ Constants.KEY_AMOUNT + " TEXT,"
+ Constants.KEY_EXPIRY_DATE + " LONG,"
+ Constants.KEY_REMINDER_DATE + " LONG,"
+ Constants.KEY_REMINDER + " Text,"
+ Constants.KEY_BANK_NAME + " TEXT);";
db.execSQL(CREATE_ALERT_TABLE);
}
I created one app for testing with two edittexts (Email and password) and 2 buttons (submit and viewdata). I was debug this application and it is working fine.
I wanted to update this application by adding one more Edittext (Name) and upgrade the SQLite Database in onUpgrade() method. The code is shown below.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="upgrade";
private static final int DATABASE_VERSION=2;
//details table details
public static final String TABLE_NAME_Details="details";
public static final String USERNAME="USERNAME";
public static final String PASSWORD="PASSWORD";
public static final String Name="Name"; //newly added column in version 2
public static final String TABLE_NAME_Details_temp="temp";
public static final String USERNAME_temp="USERNAME";
public static final String PASSWORD_temp="PASSWORD";
public static final String Name_temp="Name";
//create table statements for version 2
public static final String Create_Table_Details = "CREATE TABLE "
+ TABLE_NAME_Details + " (" + USERNAME + " TEXT PRIMARY KEY,"
+ PASSWORD + " TEXT ,"
+ Name + " TEXT"
+")";
/* creation for version 1
private static final String Create_Table_Details = "CREATE TABLE " +
TABLE_NAME_Details + "("
+ USERNAME + " TEXT PRIMARY KEY,"
+ PASSWORD + " TEXT"
+ ")";*/
//Alter table statements FOR onUpgrade()
//private static final String ALTER_Details = "ALTER TABLE " +
TABLE_NAME_Details + " ADD COLUMN" + Name + " TEXT";
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(Create_Table_Details);
Log.d("database","installed successfully");
}catch (Exception e)
{
e.printStackTrace();
Log.e("/test","Exception due to"+e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
String TEMP_CREATE_CONTACTS_TABLE = "CREATE TABLE " +
TABLE_NAME_Details_temp + "("
+ USERNAME_temp + " TEXT," + PASSWORD_temp + " TEXT )";
db.execSQL(TEMP_CREATE_CONTACTS_TABLE);
db.execSQL("INSERT INTO " + TABLE_NAME_Details_temp + " SELECT " +
USERNAME + ", "
+ PASSWORD + " FROM " + TABLE_NAME_Details);
db.execSQL("DROP TABLE "+ TABLE_NAME_Details);
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME_Details + "("
+ USERNAME + " TEXT," + PASSWORD + " TEXT," + Name + " TEXT )";
db.execSQL(CREATE_CONTACTS_TABLE);
db.execSQL("INSERT INTO " + TABLE_NAME_Details + " SELECT " +
USERNAME_temp + ", "
+ PASSWORD_temp + ", " + Name_temp + ", " + null + " FROM " +
TABLE_NAME_Details_temp);
db.execSQL("DROP TABLE " + TABLE_NAME_Details);
}
public boolean insertData(String username, String password,String name)
{
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(USERNAME,username);
contentValues.put(PASSWORD,password);
contentValues.put(Name,name);
long result=db.insertOrThrow(TABLE_NAME_Details, null, contentValues);
if(result==-1)
return false;
else
return true;
}catch(Exception e)
{
e.printStackTrace();
Log.e("/test","Exception due to"+e.toString());
return false;
}
}
//update value
public boolean updatePassword(String LoggedUsername)
{
SQLiteDatabase db = null;
try {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PASSWORD, "test");
if (db.isOpen()) {
db.update(TABLE_NAME_Details, values, USERNAME + "='" +
LoggedUsername+"'",null);
return true;
}
else
return false;
} catch (Exception e) {
Log.d("eEmp/DBUpdateUser ", e.toString());
return false;
}
}
//getting data from database
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME_Details,null);
return res;
}
}
I installed the 1st version and working fine and then uninstalled.
After uninstallation, installed the 2nd version and it stores the data. it is also working fine.
When I am trying to update the 1st version with the 2nd version in debug mode, the app updated successfully and the data that entered in the 1st version is visible. and when I am trying to store the data in 2nd version, the data is not inserting to sqlite database. Why?
While debugging, insert method is called but here if(result==-1) I am getting -1 instead of 1. so, data control comes out from the method and the data is not inserting to database.
For example: In 1st version: I entered username: stackoverflow and password stackoverflow.
and I updated the app to 2nd version and updated successfully. Now I entered username: hello password:hello name:hello and then click on submit button.
After that If I click on viewdata button: it display username: stackoverflow password stackoverflow name:null. But not displaying the data inserted in 2nd version.
Any help would be appreciated. Please help me with the correct solution.
Thank you.
Try this..
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String TEMP_CREATE_CONTACTS_TABLE = "CREATE TABLE " + TEMP_TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_ADDRESS + " TEXT)";
db.execSQL(TEMP_CREATE_CONTACTS_TABLE);
// Create an temporaty table that can store data of older version
db.execSQL("INSERT INTO " + TEMP_TABLE_CONTACTS + " SELECT " + KEY_ID + ", "
+ KEY_NAME + ", " + KEY_ADDRESS + " FROM " + TABLE_CONTACTS);
// Insert data into temporary table from existing older version database (that doesn't contains ADDRESS2 //column)
db.execSQL("DROP TABLE "+ TABLE_CONTACTS);
// Remove older version database table
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_ADDRESS2 + " TEXT )";
db.execSQL(CREATE_CONTACTS_TABLE);
// Create new table with ADDRESS2 column
db.execSQL("INSERT INTO " + TABLE_CONTACTS + " SELECT " + KEY_ID + ", "
+ KEY_NAME + ", " + KEY_ADDRESS + ", " + null + " FROM " + TEMP_TABLE_CONTACTS);
// Insert data ffrom temporary table that doesn't have ADDRESS2 column so left it that column name as null.
db.execSQL("DROP TABLE " + TEMP_TABLE_CONTACTS);
}
there is a typing mistake check it you column name is db is
public static final String Name="Name"; //newly added column in version 2
and you are using NAME_ change it while inserting data in sqlite
Try this
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(USERNAME,username);
contentValues.put(PASSWORD,password);
contentValues.put(Name,name);
long result=db.insert(TABLE_NAME_Details, null, contentValues);
if(result==-1)
return false;
else
return true;
}catch(Exception e)
{
e.printStackTrace();
Log.e("/test","Exception due to"+e.toString());
return false;
}
Don't catch exceptions in onCreate() and onUpgrade(). If there's a problem, the method must not return normally. Returning normally means everything was successful and the database schema is ready to use.
Notice the missing whitespace in your onUpgrade() ALTER TABLE:
private static final String ALTER_Details = "ALTER TABLE " + TABLE_NAME_Details + " ADD COLUMN" + NAME_ + " TEXT";
between COLUMN and NAME_. This causes the upgraded database to not work. Fresh install only goes thru onCreate() and the bug in onUpgrade() is not exposed.
Use insertOrThrow() instead of insert() to get more helpful error messages, such as "no such column".
I have made a separate class named DatabaseHelper.java and want to make a simple table named sensors.
I wish to update the table using name as a where. But I can't seem to make it work. Please check my code:
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Readings.db";
public static final String SENSORS_TABLE_NAME = "sensors";
public static final String SENSORS_COLUMN_ID = "Id";
public static final String SENSORS_COLUMN_NAME = "Name";
public static final String SENSORS_COLUMN_1 = "Reading1";
public static final String SENSORS_COLUMN_2 = "Reading2";
public static final String SENSORS_COLUMN_3 = "Reading3";
public static final String SENSORS_COLUMN_4 = "Reading4";
public static final String SENSORS_COLUMN_STATUS = "Status";
public DBHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE" + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTO INCREMENT," + SENSORS_COLUMN_NAME + "STRING" +
SENSORS_COLUMN_1 + "STRING," + SENSORS_COLUMN_2 + "FLOAT," +
SENSORS_COLUMN_3 + "FLOAT," + SENSORS_COLUMN_4 + "FLOAT," + SENSORS_COLUMN_STATUS + "BOOLEAN)"
);
db.setLocale(Locale.getDefault());
db.setVersion(1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS" + SENSORS_TABLE_NAME);
onCreate(db);
}
public boolean insertSensor(String name, boolean status)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Name", name);
contentValues.put("Reading1", 0);
contentValues.put("Reading2", 0);
contentValues.put("Reading3", 0);
contentValues.put("Reading4", 0);
contentValues.put("Status", status);
db.insert("sensors", null, contentValues);
return true;
}
public Cursor getData(String Name){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where Name="+Name+"", null );
return res;
}
public boolean updateSensor (String Name, float Reading1, float Reading2, float Reading3, float Reading4, boolean Status)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Reading1", 0);
contentValues.put("Reading2", 0);
contentValues.put("Reading3", 0);
contentValues.put("Reading4", 0);
contentValues.put("Status", Status);
db.update("sensors", contentValues, "Name="+Name, new String[]{Name});
return true;
}
}
[EDIT]
public boolean updateSensor(String Name, float Reading1, float Reading2, float Reading3, float Reading4, boolean Status) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Reading1", Reading1);
contentValues.put("Reading2", Reading2);
contentValues.put("Reading3", Reading3);
contentValues.put("Reading4", Reading4);
contentValues.put("Status", Status);
db.update("sensors", contentValues, " = ?", new String[]{Name});
return true;
}
android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: UPDATE sensors SET Reading3=?,Status=?,Reading2=?,Reading1=?,Reading4=? WHERE =
Still not working -.- getting tired
Uninstalled the app and reinstalled it multiple times.
[EDIT]
Code still not working:
public boolean updateSensor(String Name, float Reading1, float Reading2, float Reading3, float Reading4, boolean Status) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SENSORS_COLUMN_1, Reading1);
contentValues.put(SENSORS_COLUMN_2, Reading2);
contentValues.put(SENSORS_COLUMN_3, Reading3);
contentValues.put(SENSORS_COLUMN_4, Reading4);
contentValues.put(SENSORS_COLUMN_STATUS, Status);
db.update("sensors", contentValues, "Name = ?", new String[]{Name});
return true;
}
The error this time is:
android.database.sqlite.SQLiteException: no such column: Reading1 (code 1): , while compiling: UPDATE sensors SET Reading3=?,Status=?,Reading2=?,Reading1=?,Reading4=? WHERE Name = ?
[EDIT]
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + " INTEGER PRIMARY KEY," + SENSORS_COLUMN_NAME + " TEXT" +
SENSORS_COLUMN_1 + " REAL," + SENSORS_COLUMN_2 + " REAL," +
SENSORS_COLUMN_3 + " REAL," + SENSORS_COLUMN_4 + " REAL," + SENSORS_COLUMN_STATUS + " INTEGER)"
);
db.setLocale(Locale.getDefault());
db.setVersion(1);
}
Your table creation is wrong: you mess a bunch of spaces
db.execSQL("CREATE TABLE" + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTO INCREMENT," + SENSORS_COLUMN_NAME + "STRING" +
SENSORS_COLUMN_1 + "STRING," + SENSORS_COLUMN_2 + "FLOAT," +
SENSORS_COLUMN_3 + "FLOAT," + SENSORS_COLUMN_4 + "FLOAT," + SENSORS_COLUMN_STATUS + "BOOLEAN)"
);
And
db.execSQL("DROP TABLE IF EXISTS" + SENSORS_TABLE_NAME);
Should be
db.execSQL("CREATE TABLE " + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID +
" INTEGER PRIMARY KEY AUTO INCREMENT," + SENSORS_COLUMN_NAME + " TEXT" +
SENSORS_COLUMN_1 + " TEXT," + SENSORS_COLUMN_2 + " FLOAT," +
SENSORS_COLUMN_3 + " FLOAT," + SENSORS_COLUMN_4 + " FLOAT," +
SENSORS_COLUMN_STATUS + " BOOLEAN)"
);
And
db.execSQL("DROP TABLE IF EXISTS " + SENSORS_TABLE_NAME);
Note: Keeping your code well formatted would help a lot.
You also miss some ' when dealing with string values:
Cursor res = db.rawQuery( "select * from contacts where Name="+Name+"", null );
And
db.update("sensors", contentValues, "Name="+Name, new String[]{Name});
Should be:
Cursor res = db.rawQuery( "select * from contacts where Name='" + Name + "'", null );
And
db.update("sensors", contentValues, "Name='" + Name + "'", new String[]{Name});
My advice would be to use bound parameters (that syntax which usus the ? placeholders and a String array to replace them one by one).
After making all the code modifications, just uninstall and reinstall the app.
[EDIT]
You changed your code (why?!), therefore invalidating half of my answer - I hate when this happens!! I rolled back to your original post.
OK, now seeing your update code... it's wrong!
This is the correct syntax
update(String table, ContentValues values, String whereClause, String[] whereArgs)
This
db.update("sensors", contentValues, DATABASE_NAME + " = ?" + Name, new String[] {Name});
should be
db.update("sensors", contentValues, "Name = ?", new String[]{Name});
SQLite uses a more general dynamic type system. Please look at the storage classes that must have each value stored in a SQLite database:
https://www.sqlite.org/lang.html
1. onCreate
"CREATE TABLE" + SENSORS_TABLE_NAME +
"(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTO INCREMENT," +
look at: creat table --> column-def --> column-constraint
AUTOINCREMENT is only one key-word
SENSORS_COLUMN_NAME + "STRING" + SENSORS_COLUMN_1 + "STRING," +
https://www.sqlite.org/datatype3.html
There is no datatype STRING and also not, if you look at the affinity name examples.
Take TEXT, or, if you wan't to give the length, VARCHAR(length)
SENSORS_COLUMN_2 + "FLOAT," + SENSORS_COLUMN_3 + "FLOAT," +
SENSORS_COLUMN_4 + "FLOAT," +
"FLOAT" is all right and it converted into "REAL"
SENSORS_COLUMN_STATUS + "BOOLEAN)"
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).(1.1 Boolean Datatype)
I think, your statement may be:
db.execSQL("CREATE TABLE" + SENSORS_TABLE_NAME +
"(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," +
SENSORS_COLUMN_NAME + "TEXT" +
SENSORS_COLUMN_1 + "TEXT," +
SENSORS_COLUMN_2 + "FLOAT," +
SENSORS_COLUMN_3 + "FLOAT," +
SENSORS_COLUMN_4 + "FLOAT," +
SENSORS_COLUMN_STATUS + "INTEGER )"
);
"setVersion" and "setLocale" in onCreate
I do not know if that's necessary.
In the constructor you have giver the version 1:
super(context, DATABASE_NAME, null, 1);
Please look at reference/android/database/sqlite/SQLiteOpenHelper
Better is to take a string for the version, becourse an upgrate was taken when you have a new version.
public static final int DB_VERSION = 1;
And than:
super(context, DATABASE_NAME, null, DB_VERSION);
I had made SQLite database to my android application and it worked fine until I tried to add new column called "state". I have read previous posts in forum, and I tried adding new database version, modifying onUpgrade method, I have also tried deleting app, cleaning cache, and adding ALTER table but I still get error:
table has no column named state
So how do I update my database to make it work?
Here's my code
public class DatabaseHelper extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 3;
// Database Name
private static final String DATABASE_NAME = "dbase";
// Contacts table name
private static final String TABELL_BRUKERE = "bTab";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAVN = "navn";
private static final String KEY_ADR = "adresse";
private static final String KEY_BIL = "bil_kjennemerke";
private static final String KEY_STATE = "state";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT"
+ KEY_STATE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT"
+ KEY_STATE + " TEXT" + ")";
if (oldVersion < 4 )
db.execSQL(CREATE_CONTACTS_TABLE);
// Create tables again
onCreate(db);
}
public void addContact(Bruker bruker) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAVN, bruker.getNavn()); // navn
values.put(KEY_ADR, bruker.getAdresse()); // Adresse
values.put(KEY_BIL, bruker.getBilmerke()); // Bil
values.put(KEY_STATE, bruker.getState()); // state
// Inserting Row
db.insert(TABELL_BRUKERE, null, values);
db.close(); // Closing database connection
}
public int getCount() {
String countQuery = "SELECT * FROM " + TABELL_BRUKERE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Getting single contact
public Bruker getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELL_BRUKERE, new String[] { KEY_ID,
KEY_NAVN, KEY_ADR,KEY_BIL,KEY_STATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Bruker bruker = new Bruker(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4));
// return contact
return bruker;
}
// Getting All Contacts
public List<Bruker> getBrukere() {
List<Bruker> contactList = new ArrayList<Bruker>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABELL_BRUKERE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bruker bruker = new Bruker();
bruker.setID(Integer.parseInt(cursor.getString(0)));
bruker.setNavn(cursor.getString(1));
bruker.setAdresse(cursor.getString(2));
bruker.setBilmerke(cursor.getString(3));
bruker.setState(cursor.getString(4));
// Adding contact to list
contactList.add(bruker);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Deleting single contact
public void deleteContact(Bruker bruker) {}
}
create query in Oncreate method:
" CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT,"
+ KEY_STATE + " TEXT" + ")";
and
Delete query in onupgrade method :
"DROP TABLE IF EXISTS " + TABELL_BRUKERE ;
In your onCreate and onUpdate you forget to put a "," after the KEY_BIL text.
Therefore android could not "parse" you string succesfull.
so, the CREATE_CONTACTS_TABLE string should look like this:
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT," // add the "," here !!!
+ KEY_STATE + " TEXT" + ")";
KEY_BIL + " TEXT after you missed comma(,)
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT,"
+ KEY_STATE + " TEXT" + ")";
So, I've created an app which SHOULD be making a database. However, I've looked at the ADM and I've found it's not in there.
My confusion is why this is it not being created? I have:
DatabaseHandler.java
MyActivity.java
Car.java
I am calling methods from the DatabaseHandler.java inside the MyActivity. I have 0 errors in my project.
Here is my DatabaseHandler.java:
package com.example.brad.myapplication;
import android.accounts.Account;
import android.database.DatabaseUtils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import static android.database.DatabaseUtils.dumpCursorToString;
/**
* Created by Brad on 19/07/2014.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "carsGrid",
TABLE_CARS = "cars",
KEY_ID = "id",
KEY_POSTCODE = "postcode",
KEY_ADDRESS = "address",
KEY_IMAGE = "image";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE" + TABLE_CARS + ")" + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ADDRESS + " TEXT,"+ KEY_POSTCODE + " TEXT," + KEY_IMAGE + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CARS);
onCreate(db);
}
public void createCar(Car car) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ADDRESS, car.get_address());
values.put(KEY_POSTCODE, car.get_postcode());
values.put(KEY_IMAGE, car.get_image());
db.insert(TABLE_CARS, null, values);
db.close();
}
public Car getCar(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CARS, new String[] {KEY_ID, KEY_IMAGE, KEY_ADDRESS, KEY_POSTCODE}, KEY_ID + "=?", new String[] { String.valueOf(id)}, null,null,null,null);
if (cursor != null)
cursor.moveToFirst();
Car car = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3));
return car;
}
public int getCarCount() {
//SELECT * FROM CARS
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM" + TABLE_CARS, null);
cursor.close();
return cursor.getCount();
}
public String getRandomImageKey() {
//SELECT * FROM CARS
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM" + TABLE_CARS + "ORDER BY RANDOM() LIMIT 1", null);
int columnIndex = cursor.getColumnIndex(KEY_ID);
String toReturn = cursor.getString(columnIndex);
return toReturn;
}
public Car getCurrentCar() {
SQLiteDatabase db = getWritableDatabase();
String sql = "SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM " + TABLE_CARS + "ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(sql, new String[] {});
Car car = null;
try {
if (cursor.moveToFirst()) {
car = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3));
}
}
finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
}
return car;
}
}
Here is my MyActivity.java:
public class MyActivity extends Activity {
// Defining elements in XML
EditText postCodeStringTxt, DistanceNumberTxt, DebugCarTxt;
String imagestring;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Creating elements in XML
postCodeStringTxt = (EditText) findViewById(R.id.postCodeString);
DistanceNumberTxt = (EditText) findViewById(R.id.DistanceNumber);
DebugCarTxt = (EditText) findViewById(R.id.DebugCar);
// you should instantiate 'DatabaseHandler' here
DatabaseHandler db = new DatabaseHandler(this); // "this" refer to the context
Car cars = db.getCurrentCar();
db.createCar(new Car(cars.get_id(),cars.get_address(),cars.get_postcode(),cars.get_image()));
String rows= "id : "+ cars.get_id()+ " address : "+cars.get_address() + "postcode : "+cars.get_postcode()+" image : "+cars.get_image();
How can I zone into the area which isn't working if there are no errors in the project?
Change your Create Table SQL Command with below:
db.execSQL("CREATE TABLE" + TABLE_CARS + "(" + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ADDRESS + " TEXT,"+ KEY_POSTCODE + " TEXT," + KEY_IMAGE + " TEXT)");
Your DB is not created it's because your create Table SQL Command Syntax is wrong.
You should also change this
Cursor cursor = db.rawQuery("SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM" + TABLE_CARS + "ORDER BY RANDOM() LIMIT 1", null);
to
Cursor cursor = db.rawQuery("SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM " + TABLE_CARS + " ORDER BY RANDOM() LIMIT 1", null);// make space after FROM and before ORDER BY
in your getRandomImageKey() method and also do same in getCurrentCar() method
In your DatabaseHandler class create table syntax is wrong.so change this line
db.execSQL("CREATE TABLE" + TABLE_CARS + ")" + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ADDRESS + " TEXT,"+ KEY_POSTCODE + " TEXT," + KEY_IMAGE + " TEXT)");
into
db.execSQL("CREATE TABLE" + TABLE_CARS + "(" + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ADDRESS + " TEXT,"+ KEY_POSTCODE + " TEXT," + KEY_IMAGE + " TEXT)");
As Frank suggest your two rawQuery statements are wrong give space after FROM
That too close Cursor after your opeariton is done.
Not only your CREATE TABLE is wrong, as correctly pointed out by others (a reversed bracket and a missing space):
db.execSQL("CREATE TABLE" + TABLE_CARS + ")" + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ADDRESS + " TEXT,"+ KEY_POSTCODE + " TEXT," + KEY_IMAGE + " TEXT)");
should be
db.execSQL("CREATE TABLE " + TABLE_CARS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ADDRESS + " TEXT,"+ KEY_POSTCODE + " TEXT," + KEY_IMAGE + " TEXT)");
You have another issue here (missing a space):
Cursor cursor = db.rawQuery("SELECT * FROM" + TABLE_CARS, null);
should be
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CARS, null);
Try using this:
db.execSQL("CREATE TABLE" + TABLE_CARS + "(" + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ADDRESS + " TEXT,"+ KEY_POSTCODE + " TEXT," + KEY_IMAGE + " TEXT)");
Try this..
String createTableQuery=String.format(
"CREATE TABLE %s(%s INTEGER PRIMARY KEY AUTOINCREMENT,%s TEXT,%s TEXT,%s TEXT)",
TABLE_CARS, KEY_ID, KEY_ADDRESS, KEY_POSTCODE, KEY_IMAGE);
....
dB.execSQL(createTableQuery);