I am creating my SQLite database for my App at runtime if it does not exist and insert rows if it does. Since it is supposed to be created at runtime and I have implemented it by creating a subclass of SQLiteOpenHelper and overriding the onCreate() method -
"Do I need to put anything in the /assets folder of my project?"
I am not using any Content Provider "Do I need to add any tags in the AndroidManifest.xml?"
Here is what I have done. The strings have been defined properly and I do not get any runtime exceptions.
Implementation of the SQLiteOpenHelper subclass.
public class MyDB extends SQLiteOpenHelper {
public MyDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERAUTH_TABLE_CREATE);
db.execSQL(USERPREF_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and
recreate.");
db.execSQL("DROP TABLE IF EXISTS " + USERAUTH_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + USERPREF_TABLE_NAME);
onCreate(db);
}
}
Here is where I create an instance of the MyDB subclass of the SQLiteOpenHelper.
MyDB tdb = new MyDB(Activity.this);
SQLiteDatabase db = tdb.getReadableDatabase();
Everything runs and when I go to the sqlite shell and write the following query
select * from table_name - it just tells me no such record exist. I set breakpoints and it seems after the getReadableDatabase() is called the #Override OnCreate() method is never executed which is where I execute the Create table SQLs. I have tried getWritableDatabase()
as well.
I dont understand why the tables are not being created. If anyone can help that would be awesome.
Thanks.
Query Text String#1
private static final String USERAUTH_TABLE_CREATE =
"CREATE TABLE " + USERAUTH_TABLE_NAME + " (" +
"number INTEGER NOT NULL," +
"dip TEXT NOT NULL," +
"email TEXT NOT NULL," +
"password TEXT NOT NULL," +
"flag INTEGER" + ");" ;
Query Text String #2
private static final String USERPREF_TABLE_CREATE =
"CREATE TABLE " + USERPREF_TABLE_NAME + " (" +
"tpd TEXT NOT NULL ," +
"cat TEXT NOT NULL" + ");";
If onCreate() is not being called, then the database has already been created for your app. The quickest way to solve it is to delete your project on the emulator (Settings --> Applications --> Your application), and then restart your application. Alternatively you could use ADB to just drop your database -- it's up to you. Restarting the app after dropping the database will call onCreate() because the database does not exist, and then your table creation sql will be run. onCreate() is only called if your database DOES NOT exist (so pretty much the first time you call the database in your code.
"Do I need to put anything in the /assets folder of my project?"
No
"Do I need to add any tags in the AndroidManifest.xml?"
No
Your syntax is ok ... could you paste the query you are making for creating tables ?
This might be a silly question, but have you defined the DATABASE_NAME and DATABASE_VERSION variables?
Issue resolved. Code was working all the way once again. sqlite shell was not showing me the tables and the database. When I kept my app running on the emulator and navigated to data > data > your-package-name > databases > your-database-file using DDMS the system shows me the SQLite DB was created fine. I have checked the tables are there as well.
Thank you all guys!!
This simple application will create a data base and 1 table w and at the end it will
retrieve the value which u have enetered and vl show in textBox.
SQLiteDatabase myDB= null;
String TableName="Profile";
String ShowData="";
/* This function create new database if not exists. */
try {
myDB = openOrCreateDatabase("DataBase.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "+ TableName + " (id INT(4),firstname VARCHAR,lastname VARCHAR);");
/* Insert data to a Table*/
//myDB.execSQL("INSERT INTO "+ TableName +"(id, firstname, lastname) "+ " VALUES (1, 'Pir', 'Fahim');");
Toast.makeText(this," DATA BASE HAVE BEEN CREATED ", Toast.LENGTH_SHORT).show();
/*Fetch data from database table */
Cursor c = myDB.rawQuery("SELECT* FROM " + TableName , null);
int id = c.getColumnIndex("id");
int fristName = c.getColumnIndex("firstname");
int lastName = c.getColumnIndex("lastname");
// Check result.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
int personId = c.getInt(id);
String FirstName = c.getString(fristName);
String LastName = c.getString(lastName);
ShowData =ShowData +personId+" .) " +FirstName+" "+LastName+"\n";
txt.append("********************"+"\n"+personId+"\n"+FirstName+"\n"+LastName+"\n");
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
while(c.moveToNext());
}
// Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(this, "Error = "+e.getMessage(), Toast.LENGTH_LONG).show();
}
finally
{
if (myDB != null)
myDB.close();
}
Related
I'm getting this error -
07-03 12:29:18.643: E/SQLiteLog(5181): (1) table accounts has no column named otherNotes
This is my code:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "accountsManager";
private static final String TABLE_ACCOUNTS = "accounts";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_USERID = "userId";
private static final String KEY_PASSWORD = "password";
private static final String KEY_LOGINURL = "loginUrl";
private static final String KEY_OTHERNOTES = "otherNotes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_USERID + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_LOGINURL + " TEXT,"
+ KEY_OTHERNOTES + " TEXT" + ");";
db.execSQL(CREATE_ACCOUNTS_TABLE);
}
public void addAccount(AccountDetails account) {
SQLiteDatabase db = this.getWritableDatabase();
System.out.println("Hello!");
ContentValues values = new ContentValues();
values.put(KEY_TITLE, account.getTitle()); // Account Title
values.put(KEY_USERID, account.getUserId()); // account userid
values.put(KEY_PASSWORD, account.getPassword()); // account password
values.put(KEY_LOGINURL, account.getLoginUrl()); // account loginurl
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Log.v("title", KEY_TITLE);
// Inserting Row
db.insert(TABLE_ACCOUNTS, null, values);
db.close(); // Closing database connection
}
Also, when I remove the following statement:
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Then I get the same problem with password...etc.
i.e, (1) table accounts has no column named password
Please help!!
It seems that you added some columns later in the database. I do agree with Ken Wolf and you should consider uninstalling and re-installing your app. One better approach is, drop and recreate all tables in onUpdate method, and increase the db version every time you change the schema.
Well, If you are confindent about syntax for creating table, than it may happen
when you add new column in your same table, for that...
1) Unistall from your device and run it again.
OR
2) Setting -> app -> ClearData
OR
3) Change DATABASE_NAME in your "DatabaseHandler" class
( I faced same problem. But I suuceed by changing DATABASE_NAME.)
OR
4) Change DATABASE_VERSION in your "DatabaseHandler" class
(If you have added new column than it will upgrade autimatically)
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
As Benil says in a comment above, change the database version number and run the code again.
The SQL code looks fine.
I think that you forgot to call open() on your database object that you created.
add this methods to you SQL class:
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public DataBaseMain open() throws SQLException{
// Open the database to make her writeable, must be called before writing
// to database
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
// Closing the database for writing, avoids error.
ourHelper.close();
}
And use when you want to call you DB.
Try "Clear Data " of your App from Settings.
For me this problem was occuring because i was storage data on SD Card and later i added some columns.
So if you are saving on SD card delete the previous data.
For those who have similar problem and above solution is not worked then check 2 things:
Space between column name and data type like
COLUMN_NUMBER+" TEXT PRIMARY KEY) not COLUMN_NUMBER+"TEXT PRIMARY KEY)
The order of column during the creation of table should same as map for data insertion like
ContentValues values = new ContentValues();
values.put(TEST_ID, testId);
values.put(CLASS_NAME, className);
values.put(SUBJECT, subject);
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TEST_ID + " INTEGER,"
+ CLASS_NAME + " TEXT,"
+ SUBJECT + " TEXT,"
Here It is your query..TRY this.
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE "+TABLE_ACCOUNTS+"(KEY_ID INTEGER PRIMARY KEY,KEY_TITLE TEXT,KEY_USERID TEXT,KEY_PASSWORD TEXT,KEY_LOGINURL TEXT,KEY_OTHERNOTES TEXT);";
It's possible if you made a mistake in creation query and then fix it,
So in the file system you have a db, but this db possibly has no such column.
Solution:
in emulator find a db file: data/data/com.somecompany.yourapp/databases/db and remove it, then try again.
It's also possible to open this file in some sql explorer and check if there is that column.
I ran into the same issue, as I updated my database table in sqlite with new columns during testing phase.
Besides the answers that were already given above, what I found really useful to update SQLite databases (e.g. after changes) is ABD Idea, an AndroidStudio plugin that allows you to:
Uninstall App
List item
Kill App
Start App
Restart App
Clear App Data
Clear App Data and Restart
You can just specify the version like this:
private static final int VERSION = 4;
If your sure your codes are OKAY, just try uninstalling the application, then rerun it agian. This solved my issue. Hope it helped
the possible solution also (not the best one) to use different version of DB, like:
public static final int DATABASE_VERSION = 2;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
it works for me.
clearing app data from the phone settings worked in my case.
either in the android emulator, you can do the same.
Current code is
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
Now add colmn encrypted
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$encrypted INT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
if (newVersion == 2) {
val query = "ALTER TABLE $tblPassword ADD COLUMN $encrypted INT DEFAULT '0'"
db!!.execSQL(query)
}
}
Here if New user then oncreate method directly create table with encrypted value.
if Old user then onUpgrade method has check db version and alter the table
I know i have replie to this question to late but maybe someone can solve her problem with this answer.
You are put some data later in table database so the best solution is to re name your data base name.
In my case there was a query syntax error (need space b/w column name and datatype ..see attached image) in onCreate() method
to resolve it ..
I followed these steps
Correct your syntax error
change DB version number
Clear App data from settings
Uninstall and Run Your app again.]1]1
Hope it helps
Uninstall your app and reinstall your app and after that it will work fi
I have an app that gets JSON data from a server. I then put the parsed data into the android SQLite database and use the data as needed. This all works great, however, I am unable to find a method to update the whole table.
The scenario would be that this Json Data feed gets updated every week on the server. I have two Questions:
What am I missing or what is the method for updating the SQLite table? (currently this just duplicates the data)
public void updateTable(Product product){
SQLiteDatabase db = this.getWritableDatabase();
try{
ContentValues values = new ContentValues();
values.put(KEY_TYPE_NAME, product.getmProductTypeName());
// more columns here...
db.update(TABLE_NAME, values, null,null);
db.close();
}catch(Exception e){
Log.e("error:",e + "in updateData method")
}
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
Related Code in "Main Activity":
handler = new DBHandler(this);
NetworkUtils utils = new NetworkUtils(MainActivity.this);
if (handler.getProductCount() == 0 && utils.isConnectingToInternet()) {
new JsonDataParse().execute();
}`
Related Code "DBhandler" Activity:
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_TYPE_NAME + " TEXT" + ")"
That is basically my CREATE TABLE String format. I just condensed to because it has 16 columns.
This is the code I added to only delete the stored data only if there was data:
if(handler.getProductCount() == 0) {
}else{
handler.deleteData();
}
Then I just just added the delete the method as suggested:
public void deleteData() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, "1", null);
}
I'm not sure what you mean by "update the whole table". It sounds to me like you just need to delete the data in the table and then use your current method to add the new data. To delete the contents you can use:
db.delete(TABLE_NAME, "1", null);
Then call your existing method to re-populate the table from the server.
What is an ideal system for updating the data? Would it be silly and bad practice to just call the method when connected to internet?
No it wouldn't be bad practice. That makes sense, as you'll only be able to reach the server if you're connected to the internet anyway.
I'm getting this error -
07-03 12:29:18.643: E/SQLiteLog(5181): (1) table accounts has no column named otherNotes
This is my code:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "accountsManager";
private static final String TABLE_ACCOUNTS = "accounts";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_USERID = "userId";
private static final String KEY_PASSWORD = "password";
private static final String KEY_LOGINURL = "loginUrl";
private static final String KEY_OTHERNOTES = "otherNotes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_USERID + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_LOGINURL + " TEXT,"
+ KEY_OTHERNOTES + " TEXT" + ");";
db.execSQL(CREATE_ACCOUNTS_TABLE);
}
public void addAccount(AccountDetails account) {
SQLiteDatabase db = this.getWritableDatabase();
System.out.println("Hello!");
ContentValues values = new ContentValues();
values.put(KEY_TITLE, account.getTitle()); // Account Title
values.put(KEY_USERID, account.getUserId()); // account userid
values.put(KEY_PASSWORD, account.getPassword()); // account password
values.put(KEY_LOGINURL, account.getLoginUrl()); // account loginurl
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Log.v("title", KEY_TITLE);
// Inserting Row
db.insert(TABLE_ACCOUNTS, null, values);
db.close(); // Closing database connection
}
Also, when I remove the following statement:
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Then I get the same problem with password...etc.
i.e, (1) table accounts has no column named password
Please help!!
It seems that you added some columns later in the database. I do agree with Ken Wolf and you should consider uninstalling and re-installing your app. One better approach is, drop and recreate all tables in onUpdate method, and increase the db version every time you change the schema.
Well, If you are confindent about syntax for creating table, than it may happen
when you add new column in your same table, for that...
1) Unistall from your device and run it again.
OR
2) Setting -> app -> ClearData
OR
3) Change DATABASE_NAME in your "DatabaseHandler" class
( I faced same problem. But I suuceed by changing DATABASE_NAME.)
OR
4) Change DATABASE_VERSION in your "DatabaseHandler" class
(If you have added new column than it will upgrade autimatically)
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
As Benil says in a comment above, change the database version number and run the code again.
The SQL code looks fine.
I think that you forgot to call open() on your database object that you created.
add this methods to you SQL class:
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public DataBaseMain open() throws SQLException{
// Open the database to make her writeable, must be called before writing
// to database
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
// Closing the database for writing, avoids error.
ourHelper.close();
}
And use when you want to call you DB.
Try "Clear Data " of your App from Settings.
For me this problem was occuring because i was storage data on SD Card and later i added some columns.
So if you are saving on SD card delete the previous data.
For those who have similar problem and above solution is not worked then check 2 things:
Space between column name and data type like
COLUMN_NUMBER+" TEXT PRIMARY KEY) not COLUMN_NUMBER+"TEXT PRIMARY KEY)
The order of column during the creation of table should same as map for data insertion like
ContentValues values = new ContentValues();
values.put(TEST_ID, testId);
values.put(CLASS_NAME, className);
values.put(SUBJECT, subject);
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TEST_ID + " INTEGER,"
+ CLASS_NAME + " TEXT,"
+ SUBJECT + " TEXT,"
Here It is your query..TRY this.
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE "+TABLE_ACCOUNTS+"(KEY_ID INTEGER PRIMARY KEY,KEY_TITLE TEXT,KEY_USERID TEXT,KEY_PASSWORD TEXT,KEY_LOGINURL TEXT,KEY_OTHERNOTES TEXT);";
It's possible if you made a mistake in creation query and then fix it,
So in the file system you have a db, but this db possibly has no such column.
Solution:
in emulator find a db file: data/data/com.somecompany.yourapp/databases/db and remove it, then try again.
It's also possible to open this file in some sql explorer and check if there is that column.
I ran into the same issue, as I updated my database table in sqlite with new columns during testing phase.
Besides the answers that were already given above, what I found really useful to update SQLite databases (e.g. after changes) is ABD Idea, an AndroidStudio plugin that allows you to:
Uninstall App
List item
Kill App
Start App
Restart App
Clear App Data
Clear App Data and Restart
You can just specify the version like this:
private static final int VERSION = 4;
If your sure your codes are OKAY, just try uninstalling the application, then rerun it agian. This solved my issue. Hope it helped
the possible solution also (not the best one) to use different version of DB, like:
public static final int DATABASE_VERSION = 2;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
it works for me.
clearing app data from the phone settings worked in my case.
either in the android emulator, you can do the same.
Current code is
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
Now add colmn encrypted
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$encrypted INT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
if (newVersion == 2) {
val query = "ALTER TABLE $tblPassword ADD COLUMN $encrypted INT DEFAULT '0'"
db!!.execSQL(query)
}
}
Here if New user then oncreate method directly create table with encrypted value.
if Old user then onUpgrade method has check db version and alter the table
I know i have replie to this question to late but maybe someone can solve her problem with this answer.
You are put some data later in table database so the best solution is to re name your data base name.
In my case there was a query syntax error (need space b/w column name and datatype ..see attached image) in onCreate() method
to resolve it ..
I followed these steps
Correct your syntax error
change DB version number
Clear App data from settings
Uninstall and Run Your app again.]1]1
Hope it helps
Uninstall your app and reinstall your app and after that it will work fi
I am trying to insert some data into and SQLite DB on android, but the code below just does not work. Can anyone spot the issue.
db = this.openOrCreateDatabase("data_7.db", 0, null);
db.execSQL("CREATE TABLE IF NOT EXISTS 'group' (my_id TEXT NOT NULL, my_key TEXT NOT NULL)");
db.execSQL("INSERT INTO 'group' (my_id, my_key) VALUES ('abc', '123')");
db.close();
After running the code I extracted the SQLite file off the emulator and opened it using an SQLite GUI viewer, the table was created but no data was inserted.
Note:
I have searched through this site all day and could not find a
suitable answer to this issue
I would like to do this without the aid of helper methods like
.insert(). ie. I need to user pure SQL
Try out this way:
"INSERT INTO group (my_id, my_key) " + "VALUES ('" + field_one + "', '" + field_two + "')";
you have to create the table in the method onCreate() that is found on the Dababase class that you have to build like this:
public class Database extends SQLiteOpenHelper
{
public static final String DB_NAME="YourDBName";
public static final int VERSION=1;
Context context=null;
public Database(Context context)
{
super(context, DB_NAME, null, VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
try
{
String sql="CREATE TABLE group(my_id TEXT NOT NULL PRIMARY KEY, my_key TEXT NOT NULL)";
String insert="INSERT INTO group VALUES('abc','123');";
db.execSQL(sql);
db.execSQL(insert);
}
catch(Exception e)
{
Log.d("Exception", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS group");
onCreate(db);
}
}
Make sure that the old database is deleted or change the version to 2 in order to execute the query.
If you need to execute this query you need to write:
Database db=new Database();
SQLiteDatabasse read=db.getReadableDatabase();
My app's got a database with three tables in it: one to store the names of the people it tracks, one to track an ongoing event, and one - for lack of a better term - for settings.
I load the first table when the app starts. I ask for a readable database to load in members to display, and later I write to the database when the list changes. I've had no problems here.
The other two tables, however, I can't get to work. The code in the helper classes is identical with the exception of class names and column names, and (at least until the point where I try to access the table) the code to use the table is nearly identical as well.
Here's the code for my helper class (I've got a separate helper for each table, and as I said, it's identical except for class names and columns):
public class db_MembersOpenHelper extends SQLiteOpenHelper
{
public static final String TABLE_NAME = "members_table";
public static final String[] COLUMN_NAMES = new String[] {
Constants.KEY_ID,
"name",
"score"
};
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " ("
+ COLUMN_NAMES[0] + " INTEGER PRIMARY KEY autoincrement, "
+ COLUMN_NAMES[1] + " TEXT, "
+ COLUMN_NAMES[2] + " INTEGER);";
public db_MembersOpenHelper(Context context)
{
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_CREATE); }
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ".");
// Do nothing. We do not have any updated DB version
}
}
Here's how I use it successfully:
db_MembersOpenHelper membersDbHelper = new db_MembersOpenHelper(this);
SQLiteDatabase membersDb = membersDbHelper.getReadableDatabase();
Cursor membersResult = membersDb.query(TABLE_NAME, null, null, null, null, null, null);
members = new HashMap<String, Integer>();
membersResult.moveToFirst();
for(int r = 0; r < membersResult.getCount(); r++)
{
members.put(membersResult.getString(1), membersResult.getInt(2));
membersResult.moveToNext();
}
membersDb.close();
And here's where it fails:
db_PlayersOpenHelper playersDbHelper = new db_PlayersOpenHelper(this);
final SQLiteDatabase playersDb = playersDbHelper.getWritableDatabase();
if(newGame)
{
for(String name : players)
{
ContentValues row = new ContentValues();
row.put(COLUMN_NAMES[1], name);
row.put(COLUMN_NAMES[2], (Integer)null);
playersDb.insert(TABLE_NAME, null, row);
}
}
The first one works like a charm. The second results in ERROR/Database(6739): Error inserting achievement_id=null name=c
android.database.sqlite.SQLiteException: no such table: players_table: , while compiling: INSERT INTO players_table(achievement_id, name) VALUES(?, ?);
...
I did do some testing, and the onCreate method is not being called at all for the tables that aren't working. Which would explain why my phone thinks the table doesn't exist, but I don't know why the method isn't getting called.
I can't figure this out; what am I doing so wrong with the one table that I accidentally did right with the other?
I think the problem is that you are managing three tables with with three helpers, but only using one database. SQLiteOpenHelper manages on database, not one table. For example, it checks to see whether the database, not table, exists when it starts. It already does, so onCreate() does not fire.
I would manage all tables with one helper.
Let me see if I get this right. You are trying to create one database with three tables. But when you create the database, you create just one table; you are somehow instantiating the same database at a different place and wonder why its onCreate method doesn't get called. Is this a correct interpretation?
My strategy would be to try and create all three tables in the single onCreate() method.
If you are working with multiple tables, then you have to create all of the tables at once. If you have run your application first and later you update your database, then it will not upgrade your DB.
Now delete your application, then run it again.
There is one more solution but it is not proper. You can declare onOpen method in which you can call onCreate. And add IF NOT EXISTS before table name in your create table string. – Sourabh just now edit