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" + ")";
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'm trying to write two objects called 'Friend' and 'Social' to the database. Friend writes no problem, but 'Activity' wont work.
DatabaseHandler code:
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_FRIENDS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT,"
+ KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
String CREATE_ACTIVITIES_TABLE = "CREATE TABLE " + TABLE_ACTIVITIES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_FRIEND + " TEXT," + KEY_DESCRIPTION + " TEXT,"
+ KEY_DAY + " TEXT" + KEY_MONTH + " TEXT" + KEY_YEAR + " TEXT"+ KEY_FRIEND_ID + " TEXT" +")";
db.execSQL(CREATE_ACTIVITIES_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FRIENDS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACTIVITIES);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Friend friend) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, friend.getFirstName());
values.put(KEY_LASTNAME, friend.getLastName());
values.put(KEY_EMAIL, friend.getEmail());
// Inserting Row
db.insert(TABLE_FRIENDS, null, values);
db.close(); // Closing database connection
}
// Adding new social
void addSocial(Social social) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FRIEND_ID, social.getFriend_ID());
values.put(KEY_DESCRIPTION, social.getDescription());
values.put(KEY_FRIEND, social.getFriend());
values.put(KEY_DAY, social.getDay());
values.put(KEY_MONTH, social.getMonth());
values.put(KEY_YEAR, social.getYear());
// Inserting Row
db.insert(TABLE_ACTIVITIES, null, values);
db.close(); // Closing database connection
}
// Getting All Contacts
public List<Friend> getAllContacts() {
List<Friend> contactList = new ArrayList<Friend>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_FRIENDS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Friend friend = new Friend();
friend.setId(Integer.parseInt(cursor.getString(0)));
friend.setFirstName(cursor.getString(1));
friend.setLastName(cursor.getString(2));
friend.setEmail(cursor.getString(3));
// Adding contact to list
contactList.add(friend);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Getting All Activities
public List<Social> getAllActivities() {
List<Social> activityList = new ArrayList<Social>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ACTIVITIES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Social social = new Social();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
social.setId(Integer.parseInt(cursor.getString(0)));
social.setFriend(cursor.getString(1));
social.setDescription(cursor.getString(2));
social.setDay(cursor.getString(3));
social.setMonth(cursor.getString(4));
social.setYear(cursor.getString(5));
social.setFriend_ID(cursor.getString(6));
// Adding contact to list
activityList.add(social);
} while (cursor.moveToNext());
}
return activityList;
}
This is in the activity which tries to add a new social object to the DB. It does not give me and errors but shows up blank when I try to display all social objects in the database.
Social social = new Social();
List<Friend> friends = db.getAllContacts();
for(Friend friend: friends)
{
if(friend.getFirstName().equalsIgnoreCase(String.valueOf(spinner2.getSelectedItem())))
{
social.setFriend(friend.getFirstName() + friend.getLastName());
social.setFriend_ID(String.valueOf(friend.getId()));
social.setDescription(rs3.getText().toString());
social.setDay(String.valueOf(simpleDatePicker.getDayOfMonth()));
social.setMonth(String.valueOf(simpleDatePicker.getMonth()));
social.setYear(String.valueOf(simpleDatePicker.getYear()));
found = true;
}
}
if(found)
{
db.addActivity(social);
}
The following code will not create the activities table as you would expect due to commas being omitted,
String CREATE_ACTIVITIES_TABLE = "CREATE TABLE " + TABLE_ACTIVITIES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_FRIEND + " TEXT," + KEY_DESCRIPTION + " TEXT,"
+ KEY_DAY + " TEXT" + KEY_MONTH + " TEXT" + KEY_YEAR + " TEXT"+ KEY_FRIEND_ID + " TEXT" +")";
db.execSQL(CREATE_ACTIVITIES_TABLE);
That is commas have been omitted after the column type (TEXT) for the KEY_DAY column, for the KEY_MONTH column and for the KEY_YEAR column.
Rather it would create a table along the lines of (noting that variables, such as KEY_ID would be replaced with the value of the respective variable, which could affect the outcome) :-
columns:-
KEY_ID (TYPE INTEGER and the PRIMARY KEY)
KEY_FRIEND (TYPE as TEXT)
KEY_DESCRIPTION (TYPE as TEXT)
KEY_DAY (TYPE as TEXT KEY_MONTH TEXT KEY_YEAR TEXTKEY_FRIEND_ID TEXT)
As such the insert would not insert a row as columns KEY_MONTH .... KEY_FRIEND_ID would not exist.
The corrected code could be :-
String CREATE_ACTIVITIES_TABLE =
"CREATE TABLE " + TABLE_ACTIVITIES +
"(" +
KEY_ID + " INTEGER PRIMARY KEY," +
KEY_FRIEND + " TEXT," +
KEY_DESCRIPTION + " TEXT," +
KEY_DAY + " TEXT," + //<<<<<<<< added comma
KEY_MONTH + " TEXT," + //<<<<<<<< added comma
KEY_YEAR + " TEXT," + //<<<<<<<< added comma
KEY_FRIEND_ID + " TEXT" +
")";
db.execSQL(CREATE_ACTIVITIES_TABLE);
After changing the code you would need to do one of the following (note data may be lost) :-
delete the App's Data
uninstall the App
increment the Database version
When one of the above has been done you can then rerun the App.
Note the above code has not been tested so it may have some errors.
Syntax is wrong in the create table SQL. Missing commas.
Hi guys so here is my problem, I need to be able to access the unique ID of a row that is created because I created a second table that will "Connected" through the IDs. However here is my issue, whenever I try calling this method, my app crashes.. I was hoping the community could help me out here. Many Thanks.
public void addExerciseToDatabase(Exercises exercises){
SQLiteDatabase db = myDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
ContentValues nuValues = new ContentValues();
values.put(myDBHelper.COLUMN_BODYPARTNAME, exercises.get_bodyPart());
values.put(myDBHelper.COLUMN_EXERCISENAME, exercises.get_exerciseName());
long ID = db.insert(myDBHelper.TABLE_EXERCISES, null, values);
//FOR THE NEW TABLE VALUES
nuValues.put(myDBHelper.COLUMN_EXERCISENAME_ID, ID);
nuValues.put(myDBHelper.COLUMN_NUMSETS, exercises.get_numSets());
nuValues.put(myDBHelper.COLUMN_NUMWEIGHT, exercises.get_numWeight());
nuValues.put(myDBHelper.COLUMN_NUMREPS, exercises.get_numReps());
db.insert(myDBHelper.TABLE_EXERCISES_VALUE, null, nuValues);
db.close();
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
THIS method returns the EXERCISE ID, that corresponds to the exercise
passed and Bodypart passed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
public int getExerciseID(String exercise, String bodyPart) {
SQLiteDatabase db = myDBHelper.getWritableDatabase();
String query = "SELECT " + myDBHelper.COLUMN_ID + " FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " +
myDBHelper.COLUMN_BODYPARTNAME + " = " + bodyPart + " AND " +
myDBHelper.COLUMN_EXERCISENAME + " = " + exercise ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
int exerciseID = Integer.parseInt(c.getString(0));
/*int exerciseID = c.getInt(c.getColumnIndex(myDBHelper.COLUMN_ID));*/
c.close();
db.close();
return exerciseID;
}
HERES MY TABLE:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "exercises.db";
public static final String TABLE_EXERCISES = "exercises";
public static final String TABLE_EXERCISES_VALUE = "exercises_value";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_BODYPARTNAME = "bodypartname";
public static final String COLUMN_EXERCISENAME = "exercisename";
public static final String COLUMN_EXERCISENAME_ID = "exerciseid";
public static final String COLUMN_NUMSETS = "numsets";
public static final String COLUMN_NUMWEIGHT = "numweight";
public static final String COLUMN_NUMREPS = "numreps";
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_EXERCISES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_BODYPARTNAME + " TEXT NOT NULL," +
COLUMN_EXERCISENAME + " TEXT NOT NULL" +
");";
db.execSQL(query);
query = "CREATE TABLE " + TABLE_EXERCISES_VALUE + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_EXERCISENAME_ID + " INTEGER NOT NULL," +
COLUMN_NUMSETS + " INTEGER NOT NULL," +
COLUMN_NUMWEIGHT + " INTEGER NOT NULL," +
COLUMN_NUMREPS + " INTEGER NOT NULL" +
");";
db.execSQL(query);
}
Update your query as your query not contains spaces in SELECT and FROM
String query = "SELECT " + myDBHelper.COLUMN_ID + " FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " +
myDBHelper.COLUMN_BODYPARTNAME + " = " + bodyPart + " AND " +
myDBHelper.COLUMN_EXERCISENAME + " = " + exercise ;
Also can you post your logcat error.
public int getExerciseID(String exercise, String bodyPart) {
int exerciseID = 0;
SQLiteDatabase db = myDBHelper.getWritableDatabase();
String query = "SELECT " + myDBHelper.COLUMN_ID + " FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " +
myDBHelper.COLUMN_BODYPARTNAME + " = " + bodyPart + " AND " +
myDBHelper.COLUMN_EXERCISENAME + " = " + exercise ;
Cursor c = db.rawQuery(query, null);
if(c.getCount()>0){
c.moveToFirst();
exerciseID = Integer.parseInt(c.getString(0));
/*exerciseID = c.getInt(c.getColumnIndex(myDBHelper.COLUMN_ID));*/
}
c.close();
db.close();
return exerciseID;
}
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);