Related
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.
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);
This is how the table and row look like :
public static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_NAME +
"(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_INSTANT +
" TINYINT not null, " + COLUMN_CHANCE + " int not null);";
public static final String TABLE_INSERT = "INSERT INTO " + TABLE_NAME + " (" +
COLUMN_ID+"," + COLUMN_INSTANT +","+ COLUMN_CHANCE
+") VALUES (" +
"1," + "0," + "10"
+");";
And this is how I try to update them :
try {
open();
ContentValues values = new ContentValues();
values.put(column_name, value);
database.beginTransaction();
database.update(MySQLiteHelper.TABLE_NAME, values, MySQLiteHelper.COLUMN_ID + " = " + whereClause,null);
database.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
} finally {
database.endTransaction();
}
close();
The previous code would be equal to this query :
UPDATE options SET instant = 0 WHERE _id = 1
But the change is never applied. I check the table before and after the update but the values are the same, can anyone suggest anything?
You can make method to update...here is an example, change column name accordingly.
public int updateDetail(String new_name,String surname) {
ContentValues values = new ContentValues();
values.put("name", new_name);
return Db.update(TABLE_NAME ,values, SURNAME +"=?",new String[]{surname});
}
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.