values are not inserting to SQLite database - java

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".

Related

Not able to find column in sqlite

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

Won't write to database

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.

SQLite can not find new column

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" + ")";

Insert in sqlite doesn't work

i'm trying to make insert call to add row to my table in sqlite code,
every time insert return 1, and also after i insert row i check that the row was insert and it can't be found.
here is my code:
create tables:
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// create table artists
String createTableStatement1 = "CREATE TABLE " + TABLE_ARTISTS +" ("+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , "
+ KEY_ARTIST_NAME + " TEXT UNIQUE , " + KEY_ARTIST_IMAGE + " BLOB, " + KEY_ARTIST_JSON + " TEXT, "
+ KEY_ARTIST_DATE + " DATETIME DEFAULT (datetime('now')), " + KEY_ARTIST_FLAG + " INTEGER NOT NULL DEFAULT 1);";
db.execSQL(createTableStatement1);
//creat table users
String createTableStatement2 = "CREATE TABLE "+ TABLE_USERS + " ("+ KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, "
+ KEY_PROFILE_ID + " TEXT UNIQUE, " + KEY_PROFILE_JSON + " TEXT, "+ KEY_PROFILE_IMAGE + " BLOB, " + KEY_PROFILE_FLAG
+ " INTEGER NOT NULL);";
db.execSQL(createTableStatement2);
}
upgrade tables
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ARTISTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
// Create tables again
onCreate(db);
}
insert user row
public void insertUserToDB(User user)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PROFILE_FLAG, user.getProfile_flag());
values.put(KEY_PROFILE_IMAGE, user.getProfileImageByteArray());
values.put(KEY_PROFILE_JSON, user.getProfile_json());
values.put(KEY_PROFILE_ID, user.getProfile_id());
db.beginTransaction();
long result = db.insertOrThrow(TABLE_USERS, null, values);
db.endTransaction();
db.close();
}
check user in database
public boolean isUserInDB(String profileID)
{
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
String sqlStatement = "SELECT * FROM "+ TABLE_USERS +" WHERE " + TABLE_USERS + "."+ KEY_PROFILE_ID +
"=" + "\""+ profileID + "\"";
Cursor cursor = db.rawQuery(sqlStatement, null);
boolean exists = ((cursor.getCount())!=0);
cursor.close();
db.endTransaction();
db.close();
return exists;
}
any ideas?
You need to call setTransactionSuccessful() to make the endTransaction() apply your changes.
Please take a look at the documentation:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#beginTransaction()
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
The db.setTransactionSuccessful(); method is the most important part because it confirms the save of entire transactions. Without this call you will get no change in your database.

Adding a column to a table in sql java for android

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.

Categories

Resources