SQLite (1) no such table - java

When I run my android app I keep getting the error (1) no such table userTable, as far as I am aware I am creating the table in
TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null, );";
I have two other databases in this project and the are working fine, any help is welcome.
package com.weightpro.db;
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.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class usrPwdDB {
public static final String USER = "userName";
public static final String PWD = "password";
public static final String TABLE_NAME = "userTable";
public static final String DATA_BASE_NAME = "userdatabase";
public static final String KEY_ROWID = "_id";
public static final int DB_VERSION = 2;
private static final String TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null, );";
DBHelper WDBHelper;
Context mContext;
SQLiteDatabase db;
public usrPwdDB(Context mContext) {
this.mContext = mContext;
WDBHelper = new DBHelper(mContext);
}
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context) {
super(context,DATA_BASE_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS userTable");
onCreate(db);
}
}
public usrPwdDB open()
{
db = WDBHelper.getWritableDatabase();
return this;
}
public void close(){
WDBHelper.close();
}
public long insertInfo(String userName, String password){
ContentValues content = new ContentValues();
content.put(USER, userName);
content.put(PWD, password);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public boolean getUserNameAndPassword(String userName, String Password) throws SQLException {
Cursor mCursor =
db.query(true, TABLE_NAME, new String[] {USER,
PWD},USER+"='"+userName+"' AND password='"+Password+"'", null,
null, null, null, null);
if (mCursor.getCount() > 0)
{
return true;
}
return false;}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[] {USER, PWD},null,null,null,null,null);
}
}

remove the last comma , from the create table syntax,
private static final String TABLE_CREATE =
"create table userTable("
+ USER + " text not null, "
+ PWD + " text not null, );"; // remove this comma after not null
The correct syntax should be
private static final String TABLE_CREATE =
"create table userTable("
+ USER + " text not null, "
+ PWD + " text not null );";

You go wrong over here
+ USER + " text not null, " + PWD + " text not null, );"; //remove , from last text not null
correct SQL command with below
private static final String TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null);" ;

private static final String TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null,);" ;
remove "," after "text not null" and also remove ";"(semicolon) in the string, that is not needed i think,
then clear data or uninstall application then execute again
even though the creation of table failed i think next time onCreate() in SQLiteOpenHelper only executes once, so you will need to clear data of application
if you are using separate class for separate table and using same DB name, then all the tables in the first using class will be ok, and others will not be created since for a single database onCreate() function works only one, even if there is separate classes each with onCreate(),
onCreate() function creates a file in DB location of android file system when first called onCreate(), if the onCreate called again it check for the existence of DBNAME file in DB location and avoid creating if its exit, I think this is logic behind it...
so keep one onCreate() function for a single DB file and create all tables in that function

Related

How to get data from server and populate SQL database on Android?

I want to download data from the Firebase Firestore (array of names) and create the SQL table and feed the table with the data from the server. And every time I launch the app, I check version number from firebase, if it is the same as the SQL database version, and if it's not I recreate the table and populate it with new data.
Problem is I did something wrong with creating and checking the version number, so I get
android.database.sqlite.SQLiteException: Can't downgrade database from version 5 to 4.
This exception is pretty straightforward but I do not know where I messed up.
This is my SQLiteOpenHelper class
public class SQLBazaNamirnica extends SQLiteOpenHelper {
private static final String Ime_Baze = "baza_namirnica";
private static final String IME_TABELE = "tabela_namirnica";
private static final String ID_KOLONA = "id";
private static final String NAMIRNICA_KOLONA = "namirnica";
private static int VERZIJA_BAZE = 4;
SQLiteDatabase db;
Context context;
public SQLBazaNamirnica(Context context) {
super(context, Ime_Baze, null, VERZIJA_BAZE);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
this.db = sqLiteDatabase;
String kreirajTabelu = "CREATE TABLE " + IME_TABELE +
" (" + ID_KOLONA + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NAMIRNICA_KOLONA + " TEXT )";
db.execSQL(kreirajTabelu);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int staraV, int novaV) {
if(staraV != novaV)
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + IME_TABELE);
}
boolean CheckVerziju(int novaVer) {
//db = getWritableDatabase();
SQLiteDatabase _db = this.getWritableDatabase();
Log.d("SQL VERZIJA", "CheckVerziju: VERZIJA BAZE: " + _db.getVersion() + " \n VERZIJA FIREBASE BAZE: " + novaVer);
if(_db.getVersion() != novaVer) {
//VERZIJA_BAZE = novaVer;
_db.setVersion(novaVer);
return true;
} else return false;
}
void KreirajTabelu() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + IME_TABELE);
String kreirajTabelu = "CREATE TABLE " + IME_TABELE +
" (" + ID_KOLONA + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NAMIRNICA_KOLONA + " TEXT )";
db.execSQL(kreirajTabelu);
Log.d("SQL", "KreirajTabelu: BAZA JE KREIRANA");
}
void updateBazu(SQLiteDatabase db, ArrayList<String> namirnice) {
db = getWritableDatabase();
ContentValues cv = new ContentValues();
for(String namirnica : namirnice) {
/* String query = "INSERT INTO " + IME_TABELE + " (" +
NAMIRNICA_KOLONA + ") VALUES (" + namirnica + ")"; */
cv.put(NAMIRNICA_KOLONA, namirnica);
db.insert(IME_TABELE, null, cv);
}
}
}
And this is how I'm the checking version number :
bazaNamirnica = new SQLBazaNamirnica(MainActivity.this);
namirniceDokument.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()) {
int verzijaBaze = documentSnapshot.getLong("verzija").intValue();
if(bazaNamirnica.getReadableDatabase().getVersion() != verzijaBaze) {
//bazaNamirnica.ve
bazaNamirnica.KreirajTabelu();
Map<String, Object> namirnice = documentSnapshot.getData();
ArrayList<String> namirniceFinal = new ArrayList<>();
for(Map.Entry<String, Object> namirnica : namirnice.entrySet()) {
namirniceFinal.add(namirnica.getValue().toString());
}
bazaNamirnica.updateBazu(bazaNamirnica.getWritableDatabase(), namirniceFinal);
bazaNamirnica.getWritableDatabase().setVersion(verzijaBaze);
}
First of all, you should always consider checking if you have an updated version which is greater than your current version of the database. The onUpgrade function will only be called when there is an increase in the database version.
I am not sure what are the data that you are getting from the firebase database. However, I would like to suggest some changes to your code.
Instead of checking not equal, you might consider checking if the database version is greater like the following.
if (bazaNamirnica.getReadableDatabase().getVersion() < verzijaBaze) {
// Do the upgrade operation.
}
And also, I am not sure what you are trying to do on the version update. However, if you are dropping a table, you might need to create a new one with the updated structure that you need while upgrading your database.
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int staraV, int novaV) {
// if(staraV != novaV) // Not necessary, as this will be called on increase in the database version.
// So you have dropped the table here
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + IME_TABELE);
// Should create a new one with the updated database schema that you got
createDatabaseTableWithUpdatedSchema();
}
Hope that helps!

Android - Check if row exists in table and update it

Unfortunately all the solutions I could find, would not help me with my problem.
With a button click I want to add some value to my database table, but first it should check if the row already exists in my table, if so it just should update the row.
Here are my Codes:
MAIN ACTIVITY: (Just the Button Click)
ingredient= new Ingredient();
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < dataSource.size();i++){
tvname = (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvName);
tvamount = (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvAmount);
String nameTV = tvname.getText().toString();
String amountTV = tvamount.getText().toString();
ingredient.setName(nameTV);
ingredient.setAmount(amountTV);
ingredient.setId(i);
TableIngredient.getInstance(IngredientShopping.this).checkRow(ingredient);
}
DATABASE TABLE:
public class TableIncredient extends SQLiteOpenHelper {
public static TableIngredient INSTANCE = null;
public static final String DB_NAME = "INGREDIENT_TABLE";
public static final int VERSION = 1;
public static final String TABLE_NAME = "ingredient_table";
public static final String KEY_ID = "ID";
public static final String COL_NAME = "Name";
public static final String COL_AMOUNT = "AMOUNT";
public TableIngredient (Context context) {
super(context, DB_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE " + TABLE_NAME
+ "(" + KEY_ID + " INTEGER PRIMARY KEY, "
+ COL_NAME + " TEXT NOT NULL, "
+ COL_AMOUNT + " INTEGER DEFAULT NULL)";
db.execSQL(createQuery);
}
public boolean checkRow(Ingredient ingredient){
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME,
new String[]{KEY_ID, COL_NAME, COL_AMOUUNT},
KEY_ID + " =? AND " + COL_NAME + " =? AND " + COL_AMOUNT + " =?" ,
new String[]{String.valueOf(ingredient)},
null, null, null, null);
ContentValues values = new ContentValues();
values.put(COL_NAME, ingredient.getName());
values.put(COL_AMOUNT, ingredient.getAmount());
if (c.moveToFirst()){
increseIngredient(ingredient);
return true;
}
else {
long newID = db.insert(TABLE_NAME, null, values);
db.close();
getIngredient(newID);
return false;
}
}
}
With this code it always uses the else statement and I do not know why this happens.
I hope someone can help me to create a new row if it not exists and update the row if it exists.
With this code it always uses the else statement and I do not know why
this happens.
The reason why this happens is that the 4th parameter to the query method is new String[]{String.valueOf(ingredient)}
This will resolve to being a value something like Ingredient#1091 do you have an ingredient row that has an ID like that (rhetorical as that cannot be the case due to the ID column being an alias of the rowid and therefore ONLY integer values can be stored).
The reason that Ingredient#1091 is that the String value of the Ingredient object will be a pointer to the object.
As such no rows will ever be returned.
If instead you used new String[]{String.valueOf(ingredient.getId),ingredient.getName,ingredient.getAmount)}
The 3 values would (should), be the correct values (assuming that the ID is stored correctly in the Ingredient).

Unable to start activity in device

I'm trying to follow this tutorial, but I'm getting this error message, when I run on my device:
08-04 01:40:12.820 27896-27896/com.filipeferminiano.quiz E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.filipeferminiano.quiz/com.filipeferminiano.quiz.MyActivity}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.filipeferminiano.quiz/databases/triviaQuiz
How can I solve this?
Try to replace this class,hope this will help you to solve your problem.
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "triviaQuiz";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; //correct option
private static final String KEY_OPTA= "opta"; //option a
private static final String KEY_OPTB= "optb"; //option b
private static final String KEY_OPTC= "optc"; //option c
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
+KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT)";
db.execSQL(sql);
addQuestions(db);
}
private void addQuestions(SQLiteDatabase db)
{
Question q1=new Question("Which company is the largest manufacturer" +
" of network equipment?","HP", "IBM", "CISCO", "C");
this.addQuestion(q1,db);
Question q2=new Question("Which of the following is NOT " +
"an operating system?", "SuSe", "BIOS", "DOS", "B");
this.addQuestion(q2,db);
Question q3=new Question("Which of the following is the fastest" +
" writable memory?","RAM", "FLASH","Register","C");
this.addQuestion(q3,db);
Question q4=new Question("Which of the following device" +
" regulates internet traffic?", "Router", "Bridge", "Hub","A");
this.addQuestion(q4,db);
Question q5=new Question("Which of the following is NOT an" +
" interpreted language?","Ruby","Python","BASIC","C");
this.addQuestion(q5,db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
// Create tables again
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest,SQLiteDatabase db) {
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
// Inserting Row
db.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
dbase.close();
return quesList;
}
public int rowcount()
{
int row=0;
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row=cursor.getCount();
return row;
}
}
the trace already told u the reason why it crashed:
attempt to re-open an already-closed object: SQLiteDatabase
check your database objects it closed some where in your code also check in tutorial there are not anywhere write db.close() so do not close your data base in your example..
thats it...

Android SQLite Database, creating the database and DDMS perspective

For my internship I'm working on an Android application, and trying to get a local database running to set up for offline referal as well as preventing new BasicAuth requests and a required database pull every time the user returns to a certain activity. To achieve this, I'm trying to set up a SQLite database, but things are not really working out.
I'm currently using this tutorial to try and set up the database. For my application specifically I edited the MySQLiteHelper and TicketsDataSource classes.
MySQLiteHelper:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_TICKETS = "tickets";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TICKET_ID = "ticketId";
public static final String COLUMN_TICKET_TITLE = "ticketTitle";
public static final String COLUMN_PROJECT_NAME = "projectName";
public static final String COLUMN_CLIENT_NAME = "clientName";
public static final String COLUMN_TICKET_DESCRIPTION = "ticketDescription";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;
// Database creation SQL statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_TICKETS
+ "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_TICKET_ID + " text not null, "
+ COLUMN_TICKET_TITLE+ " text not null, "
+ COLUMN_PROJECT_NAME+ " text not null, "
+ COLUMN_CLIENT_NAME+ " text not null, "
+ COLUMN_TICKET_DESCRIPTION+ " text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TICKETS);
onCreate(db);
}
}
TicketsDataSource:
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class TicketsDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_TICKET_ID, MySQLiteHelper.COLUMN_TICKET_TITLE, MySQLiteHelper.COLUMN_PROJECT_NAME,
MySQLiteHelper.COLUMN_CLIENT_NAME, MySQLiteHelper.COLUMN_TICKET_DESCRIPTION};
public TicketsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Ticket createTicket(String ticket) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_TICKET_DESCRIPTION, ticket);
long insertId = database.insert(MySQLiteHelper.TABLE_TICKETS, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_TICKETS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Ticket newTicket = cursorToTicket(cursor);
cursor.close();
return newTicket;
}
public void deleteTicket(Ticket ticket) {
long id = ticket.getId();
System.out.println("Ticket deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_TICKETS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<Ticket> getAllTickets() {
List<Ticket> tickets = new ArrayList<Ticket>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_TICKETS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Ticket ticket = cursorToTicket(cursor);
tickets.add(ticket);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return tickets;
}
private Ticket cursorToTicket(Cursor cursor) {
Ticket ticket = new Ticket();
ticket.setId(cursor.getLong(0));
ticket.setTicketId(cursor.getLong(1));
ticket.setTicketTitle(cursor.getString(2));
ticket.setClientName(cursor.getString(3));
ticket.setProjectName(cursor.getString(4));
ticket.setTicketDescription(cursor.getString(5));
return ticket;
}
}
In my activity, I then call the TicketsDataSource class by first defining it:
private TicketsDataSource datasource;
And then calling it from an if-statement that checks if the server has been called succesfully already:
else {
datasource = new TicketsDataSource(this);
datasource.open();
}
Unfortunately, when I switch to the DDMS view, I can't see any database being created after I run the application multiple times. In fact, I can't even see any other folders within the main "data" folder in the DDMS view. I'm not getting any error messages (except for an 'eglSurfaceAttrib not implemented', which seems to be irrelevant after some searching on google) at this moment, but when I place a system print in the onCreate function of the MySQLiteHelper class, it does not print anything in the log (it does appear in the else-statement). I'm not sure if my Java-code is faulty, or if there's something wrong with my general setup.
Thanks in advance for your help,
Dennis
You'll only be able to see files/folders in the /data folder if you're
a: using the emulator, or
b: using a rooted phone. Those are protected folders and can't be viewed by mere mortals.
The real test of what you've written is this - can you write to and read from the database?
The best android db troubleshooting solution for me was to add this method to my SQliteHelper class which will copy your sqlite db to the sd card on the device your testing on. You can then open it up using any number of sqlite manager desktop apps and verify your tables and data. You don't need to root the phone this way. While developing, I stick calls to this method where i need to get a snapshot of the db:
public static void backup() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//com.example//databases//" + DATABASE_NAME;
String backupDBPath = DATABASE_VERSION + DATABASE_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, "//Download//" + backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
you need to add external storage permissions to your manifest.

the table still cannot be created. what is the problem?

This is my Database class
public class ProgramDbAdapter{
public static final String KEY_ROWID = "_id";
public static final String KEY_PROGRAM_TITLE = "ProgramTitle";
public static final String KEY_PROGRAM_DATE = "ProgramDate";
public static final String KEY_PROGRAM_TIME = "ProgramTime";
public static final String KEY_PROGRAM_CHANNEL = "ProgramChannel";
private static final String DATABASE_CREATE =
"CREATE TABLE " + DATABASE_TABLE + " (" + "_id integer primary key autoincrement, "
+ "ProgramTitle text, " + "ProgramDate varchar(20), "
+ "ProgramTime varchar(20), " + "ProgramChannel text)";
private static final String DATABASE_UPGRADE = "DROP TABLE IF EXISTS " + DATABASE_TABLE;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL(DATABASE_UPGRADE);
onCreate(db);
}
}
public ProgramDbAdapter open() throws SQLException{
mDbHelper = new DatabaseHelper(mcontext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public long CreateData(String ProgramTitle, String ProgramDate, String ProgramTime, String ProgramChannel){
ContentValues initialvalues = new ContentValues();
initialvalues.put(KEY_PROGRAM_TITLE, ProgramTitle);
initialvalues.put(KEY_PROGRAM_DATE, ProgramDate);
initialvalues.put(KEY_PROGRAM_TIME, ProgramTime);
initialvalues.put(KEY_PROGRAM_CHANNEL, ProgramChannel);
return mDb.insert(DATABASE_TABLE, null, initialvalues);
}
}
This is my main class
public class Program extends ExpandableListActivity{
public void onCreate(Bundle savedInstanceState) {
mDbHelper = new ProgramDbAdapter(this);
mDbHelper.open();
mDbHelper.CreateData("a","a","a","a");
}
}
when i call open() and createdata function, the logcat tell me no such table:Program. where is the problem is?
There is no varchar type in sqlite, see here. Use text instead.
I don't see where 'DATABASE_TABLE' is coming from.
Also, you should use the "rawQuery()", "query()"-Methods or a "SQLiteStatement" to bind parameters into your SQL-Statement.
And last but not least, SQLite doesn't know any 'varchar'. Check here for all Data types: Link
varchar is translated to text ...
from vladimir link:
If the declared type of the column
contains any of the strings "CHAR",
"CLOB", or "TEXT" then that column has
TEXT affinity. Notice that the type
VARCHAR contains the string "CHAR" and
is thus assigned TEXT affinity.
problem is that u created db in first run and there was different Create statment ...
delete app data from android settings or change DATABASE_VERSION

Categories