I am learning how to create and insert values into SQLite DB. the application has a button and chronometer. clicking the button starts the timer and clicking it again stops it. On stop, the values are to be stored into the DB. I can see from the file explorer in Android Studio that the DB and the table is getting created. There is evidence in the Log to suggest the start and stop time is also getting captured, but the values are not getting inserted into the DB. I am pasting snippet of the code used to create the DB and then to insert the record. I am also pasing snippet of the log where the error is output. Please help.
import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; import android.util.Log; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Feeds.db";
public static String TIMESTAMP_START;
public static String TIMESTAMP_END;
public static int _ID = 0;
public static final String DATABASE_TABLE = "T_FEEDRECORDS";
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE T_FEEDRECORDS ( _ID INTEGER primary key autoincrement, TIMESTAMP_START TEXT, TIMESTAMP_END TEXT)" ;
public DBHelper(Context context)
{
super(context,DATABASE_NAME, null, DATABASE_VERSION );
}
public void onCreate(SQLiteDatabase db)
{
Log.d("onCreate", "before DB Create");
try {
db.execSQL(SQL_CREATE_ENTRIES);
} catch(SQLException ex){ Log.d("onCreate", "DB creation exception:"+ ex.getMessage()); }
Log.d("onCreate", "after DB Create" + db.toString());
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF IT EXISTS " + DATABASE_TABLE);
Log.d("onUpgrade", "dropping table");
onCreate(db);
}
public void createFeedRecord (FeedRecords feedRecord){
ContentValues feedContent = new ContentValues();
feedContent.put(TIMESTAMP_START, feedRecord.getStartTime());
feedContent.put(TIMESTAMP_END, feedRecord.getEndTime());
try {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("createFeedRecord values before insert", "start time : " + feedRecord.getStartTime() + " Timer end:" + feedRecord.getEndTime());
db.insertOrThrow(DATABASE_TABLE,null, feedContent );
db.close();
} catch(SQLException ex) {Log.d("SQL Exdception in create feed record", "" + ex.getLocalizedMessage());}
Log.d("createFeedRecord", "after content values");
}
}
LOG SNIPPET
02-04 09:57:43.287 2213-2213/? D/onClick......﹕ Timer Start time: 150204_095743
....
02-04 10:01:25.738 2213-2213/? D/onClick......﹕ Timer Stop time: 150204_100125
02-04 10:01:25.738 2213-2213/? D/inster Time Record﹕ after create Feed
02-04 10:01:25.754 1239-1293/? W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
02-04 10:01:25.763 2213-2213/? D/createFeedRecord values before insert﹕ start time : 150204_095743 Timer end:150204_100125
02-04 10:01:25.763 2213-2213/? E/SQLiteLog﹕ (1) near "null": syntax error
02-04 10:01:25.763 2213-2213/? D/SQL Exdception in create feed record﹕ near "null": syntax error (code 1): , while compiling: INSERT INTO T_FEEDRECORDS(null) VALUES (?)
02-04 10:01:25.763 2213-2213/? D/createFeedRecord﹕ after content values
You need to assign
public static String TIMESTAMP_START="TIMESTAMP_START";
public static String TIMESTAMP_END="TIMESTAMP_END";
OR
Directly provide column name
ContentValues feedContent = new ContentValues();
feedContent.put("TIMESTAMP_START", feedRecord.getStartTime());
feedContent.put("TIMESTAMP_END", feedRecord.getEndTime());
Related
This is my App tab shows
E/SQLiteLog: (1) no such table: quest
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.developmethis.csguide.csquizmodule, PID: 22684
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.developmethis.csguide.csquizmodule/com.developmethis.csguide.csquizmodule.MainActivity}: android.database.sqlite.SQLiteException: no such table: quest (code 1): , while compiling: SELECT * FROM quest WHERE q_id='cp1'
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2480)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2540)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5781)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: android.database.sqlite.SQLiteException: no such table: quest (code 1): , while compiling: SELECT * FROM quest WHERE q_id='cp1'
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:891)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:502)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:68)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1402)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1341)
at com.developmethis.csguide.csquizmodule.DbHelper.getAllQuestions(DbHelper.java:96)
at com.developmethis.csguide.csquizmodule.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2433)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2540)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5781)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
I have copied the SQLite file into assets folder.this is my directory
What happening is I copied the file from the assets folder and then I'm trying to read data from the SQL table quest although I have double checked the data in the SQLite file through DB browser
This is the view from DB browser
Here is the code of my DBhelper class :
package com.developmethis.csguide.csquizmodule;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "sample.sqlite";
public static final String TABLE_QUEST = "quest";
public static final String KEY_QUIZ_ID = "q_id";
private final static String DB_PATH = "/data/data/package com.developmethis.csguide/databases/";
String dbName;
Context context;
File dbFile;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
this.context = context;
this.dbName = DATABASE_NAME;
dbFile= new File(DB_PATH + DATABASE_NAME);
}
#Override
public synchronized SQLiteDatabase getWritableDatabase() {
if(!dbFile.exists()){
SQLiteDatabase db = super.getWritableDatabase();
copyDataBase(db.getPath());
}
return super.getWritableDatabase();
}
#Override
public synchronized SQLiteDatabase getReadableDatabase() {
if(!dbFile.exists()){
SQLiteDatabase db = super.getReadableDatabase();
copyDataBase(db.getPath());
}
return super.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
private void copyDataBase(String dbPath){
try{
InputStream assestDB = context.getAssets().open("databases/"+dbName);
OutputStream appDB = new FileOutputStream(dbPath,false);
byte[] buffer = new byte[1024];
int length;
while ((length = assestDB.read(buffer)) > 0) {
appDB.write(buffer, 0, length);
}
appDB.flush();
appDB.close();
assestDB.close();
}catch(IOException e){
e.printStackTrace();
}
}
public List<question> getAllQuestions(String quizID) {
SQLiteDatabase dbase;
List<question> quesList = new ArrayList<question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST+" WHERE "+KEY_QUIZ_ID+"='"+quizID+"'";
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(cursor.getColumnIndex("id")));
quest.setQUIZ_ID(cursor.getString(cursor.getColumnIndex("q_id")));
quest.setQUESTION(cursor.getString(cursor.getColumnIndex("question")));
quest.setANSWER(cursor.getString(cursor.getColumnIndex("answer")));
quest.setOPTA(cursor.getString(cursor.getColumnIndex("opta")));
quest.setOPTB(cursor.getString(cursor.getColumnIndex("optb")));
quest.setOPTC(cursor.getString(cursor.getColumnIndex("optc")));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
return quesList;
}
}
This is the view from DB browser
Your view from db browser shows that the asset file is in the assets folder/directory. Your code :-
InputStream assestDB = context.getAssets().open("databases/"+dbName);
Is saying to look in assets/databases folder/directory.
Either
a) create a databases directory in the assets directory and move sample.sqlite into the databases directory.
or
b) change the code to InputStream assestDB = context.getAssets().open(dbName);
I would also suggest using :-
dbFile= new File(context.getDatabasePath(dbname));
dbfile.mkdirs();
instead of :-
dbFile= new File(DB_PATH + DATABASE_NAME);
You can then do sway with the DB_PATH variable.
This will then get the appropriate path name and if need be create any directories if they don't exist (sometimes I've come across the databases directory not existing).
Note! Only re-run the App after deleting the App's data or uninstalling the App. If you do not then the check for the existing database will find one and not copy the database.
PS as you're trapping the exceptions (
try....
catch(IOException e){
e.printStackTrace();
}
) when copying the asset file, you should always check the log for stack traces prior to an error. You would have had these.
Did you try CREATE TABLE IF NOT EXISTS after opening db:
val db = openOrCreateDatabase(path, null)
db.execSQL("CREATE TABLE IF NOT EXISTS (Varchar,VARCHAR-or-XYZZ);")
or equivalent in java if your code is in java.
I am a bit new to SQLite so please bear with me. I am creating a table and trying to access data from it but somehow I am getting this error.
android.database.sqlite.SQLiteException: no such table: table_image (code 1): , while compiling: SELECT image_data FROM table_image WHERE image_name= ' a '
Things that I did after the error came:
1.) Uninstalled the app and installed it again.
2.) Checked for spaces in the table creation code. It looks right to me.
I am not sure why this error is appearing then. Can someone please help me.
Thanks !!
My DatabaseHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database_name";
// Table Names
public static final String DB_TABLE = "table_image";
// column names
public static final String KEY_NAME = "image_name";
public static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + " ("+
KEY_NAME + " TEXT, " +
KEY_IMAGE + " BLOB"+")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
}
Adding stuff to db in another class
// Calling addEntry
addEntry(name, img);
// Function to add entry
public void addEntry( String name, byte[] image) throws SQLiteException {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.KEY_NAME, name);
cv.put(DatabaseHelper.KEY_IMAGE, image);
database.insert(DatabaseHelper.DB_TABLE, null, cv);
}
Then I am tying to get data from it.
SQLiteDatabase db = openOrCreateDatabase(DatabaseHelper.DB_TABLE, MODE_PRIVATE, null);
String selectQuery = "SELECT image_data FROM "+DatabaseHelper.DB_TABLE+" WHERE image_name= ' "+"a"+" ' ";
Cursor cursor = db.rawQuery(selectQuery,null);
byte[] image = cursor.getBlob(1);
openOrCreateDatabase() is not using SQLiteOpenHelper where you have the table creation code.
To get a SQLiteDatabase managed by SQLiteOpenHelper, call e.g. getWritableDatabase() on your helper object.
After fixing that, uninstall the app once more to get rid of the empty database created by openOrCreateDatabase().
Have you tried uninstalling your app and running it again?
error says "no such table: table_image", this situation can occur if you test your app with a DB with lesser number of tables and introduce a table later on.
once you relaunch your app with an additional table an older version of DB is already present and onCreate of your DBHelper will not be called and the new table will not be added in your db.
uninstalling the app will clear any previous instance of DB and onCreate will be called again and you will start with a fresh tables.
I know that there are a lot of topics on this error but I tried a lot of solutions and still I am stuck whit this error.
It´s my first time playing around with SQLite, and I don´t understand what is happening wrong there.
05-26 08:34:20.369 23124-23124/com.danynuria.fmp D/ODOperations﹕ Overall Table Created
05-26 08:34:20.373 23124-23124/com.danynuria.fmp E/SQLiteLog﹕ (1) no such table: database_info
05-26 08:34:20.374 23124-23124/com.danynuria.fmp E/SQLiteDatabase﹕ Error inserting date=26 / 4 / 2015 county=Bedfordshire co2_saved=149 distance=1245 distance_type=run user_id=1
android.database.sqlite.SQLiteException: no such table: database_info (code 1): , while compiling: INSERT INTO database_info(date,county,co2_saved,distance,distance_type,user_id) VALUES (?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.danynuria.fmp.OverallDatabaseOperations.putInformation(OverallDatabaseOperations.java:73)
at com.danynuria.fmp.MainActivity$1.onClick(MainActivity.java:121)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-26 08:34:20.374 23124-23124/com.danynuria.fmp D/ODOperations﹕ One row inserted
And my code:
package com.danynuria.fmp;
import android.app.DownloadManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.danynuria.fmp.OverallTableData.OverallTableinfo;
import java.sql.SQLException;
public class OverallDatabaseOperations extends SQLiteOpenHelper {
// Create integer that register version of database
private static final int overallDatabase_version = 1;
// Create query
public String CREATE_QUERY = "CREATE TABLE "+OverallTableinfo.OVERALL_TABLE_NAME+"( "+OverallTableinfo.USER_ID+" INTEGER, "+OverallTableinfo.DISTANCE+
" INTEGER, "+OverallTableinfo.DISTANCE_TYPE+" TEXT, "+OverallTableinfo.COUNTY+" TEXT, "+OverallTableinfo.CO2_SAVED+
" INTEGER, "+OverallTableinfo.DATE+" TEXT);";
// Creating the database using SQLiteOpenHelper constructor
public OverallDatabaseOperations(Context context) {
super(context, OverallTableinfo.OVERALL_DATABASE_NAME, null, overallDatabase_version);
}
public void onCreate(SQLiteDatabase odb ){
odb.execSQL(CREATE_QUERY);
Log.d("ODOperations", "Overall Table Created");
}
public void onUpgrade(SQLiteDatabase arg0,int arg1, int arg2){
}
// Create a method to insert data into database
public void putInformation(OverallDatabaseOperations dop, Integer id, Integer distance, String type, String county, Integer co2saved, String date) {
// Create a SQLite database object
SQLiteDatabase OSQ = dop.getWritableDatabase();
// Create an object for content values
ContentValues ncv = new ContentValues();
// Passing the first column value
ncv.put(OverallTableinfo.USER_ID, id);
ncv.put(OverallTableinfo.DISTANCE, distance);
ncv.put(OverallTableinfo.DISTANCE_TYPE, type);
ncv.put(OverallTableinfo.COUNTY, county);
ncv.put(OverallTableinfo.CO2_SAVED, co2saved);
ncv.put(OverallTableinfo.DATE, date);
// Inserting data into table
OSQ.insert(OverallTableinfo.OVERALL_DATABASE_NAME, null, ncv);
Log.d("ODOperations", "One row inserted");
}
}
And the other class:
package com.danynuria.fmp;
import android.provider.BaseColumns;
public class OverallTableData {
// Create constructor
public OverallTableData() {
}
// Create abstract class
public static abstract class OverallTableinfo implements BaseColumns {
// Create first column in database
public static final String USER_ID = "user_id";
// Create second column in database
public static final String DISTANCE = "distance";
// Create third column in database
public static final String DISTANCE_TYPE = "distance_type";
// Create forth column in database
public static final String COUNTY = "county";
// Create fifth column in database
public static final String CO2_SAVED = "co2_saved";
// Create sixth column in database
public static final String DATE = "date";
// Define database name
public static final String OVERALL_DATABASE_NAME = "database_info";
// Define table name
public static final String OVERALL_TABLE_NAME = "overall_info";
}
}
Any suggestions are highly appreciated
you have to use OVERALL_TABLE_NAME instead of OVERALL_DATABASE_NAME in your insert:
OSQ.insert(OverallTableinfo.OVERALL_TABLE_NAME, null, ncv);
I have written a code that get information from json file related to specific YouTube video and then stores the information I need in my database.
The parsing from json file has no problem. when I am trying to insert values in my database an error message appears telling me that no such table exists.
Here is the stack-trace:
07-31 08:42:22.451: I/Database(365): sqlite returned: error code = 1,
msg = no such table: youtube_VIDEOS 07-31 08:42:22.471: E/Database(365):
Error inserting video_CommentCount=70 video_CountView=50 video_Name=Badly
Drawn Boy - Disillusion (directed by Garth Jennings)
video_Url=https://www.youtube.com/watch?v=B11msns6wPU&feature=youtube_gdata_player
video_LIKES=60 video_Img=https://i1.ytimg.com/vi/B11msns6wPU/default.jpg
video_Descrption=My new playlist Description 07-31 08:42:22.471:
E/Database(365): android.database.sqlite.SQLiteException:
no such table: youtube_VIDEOS: ,
while compiling: INSERT INTO youtube_VIDEOS(video_CommentCount, video_CountView, video_Name, video_Url,video_LIKES, video_Img, video_Descrption) VALUES(?, ?, ?, ?, ?, ?, ?);
07-31 08:42:22.471: E/Database(365): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
And here is my database code:
package com.example.tstnetconnwithjson.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class youtube_db extends SQLiteOpenHelper {
public static final String dataBase_NAME="YOUTUBE_database";
private static final int dataBase_VERSION=1;
private static final String dataBase_TABLE="youtube_VIDEOS";
public static final String[] COLS_List={"video_Name","video_Descrption","video_Img","video_Url","video_CountView","video_LIKES","video_CommentCount"};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//end of declaring attributes and tables conents
public youtube_db(Context context) {
super(context,dataBase_NAME, null, dataBase_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + dataBase_NAME + "(" + COLS_List[0] +" text not null , "+ COLS_List[1]
+" text not null , "+ COLS_List[2]+" text not null , "+COLS_List[3]+" text not null , "+COLS_List[4]+" integer , "+COLS_List[5]
+" integer , "+COLS_List[6]+" integer ) ");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.i("in the upgrade", "ok");
}
}
And here is the function that would insert the information in my database:
package com.example.tstnetconnwithjson.db;
import com.example.tstnetconnwithjson.tables.videos;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class youtubeDataBaseManager {
SQLiteDatabase SQL_db;
youtube_db my_Database;
public youtubeDataBaseManager(Context c){
my_Database=new youtube_db(c);
SQL_db= my_Database.getWritableDatabase();
}//end of costructor
public long insert_Youtube_Info( videos video){
ContentValues contentValues = new ContentValues();
contentValues.put(youtube_db.COLS_List[0], video.getVideoname());
contentValues.put(youtube_db.COLS_List[1], video.getDecscrption());
contentValues.put(youtube_db.COLS_List[2], video.getImageurl());
contentValues.put(youtube_db.COLS_List[3], video.getVediourl());
contentValues.put(youtube_db.COLS_List[4], "50");
contentValues.put(youtube_db.COLS_List[5], "60");
contentValues.put(youtube_db.COLS_List[6], "70");
long addResult ;
addResult= SQL_db.insert(youtube_db.dataBase_TABLE, null, contentValues);
if(addResult==-1)
{
Log.i("add video", "add error.... ");
}
else
{
Log.i("add video", "add:ok.... ");
}
return addResult;
}
Can anyone tell me what is the problem?
"create table" + dataBase_NAME + "("
You are missing space between name and <create table> keyword. You have to change it to:
"create table " + dataBase_TABLE + "("
Otherwise, your DDL statement won't work.
Later, you try and reference a table called "youtube_VIDEOS", which doesn't exist. Because you never created it. It's all about typo.
you should change here:
create table" + dataBase_TABLE+ "(" + COLS_List[0] +" text not null , "+ COLS_List[1]
+" text not null , "+ COLS_List[2]+" text not null , "+COLS_List[3]+" text not null , "+COLS_List[4]+" integer , "+COLS_List[5]
+" integer , "+COLS_List[6]+" integer ) ");
You have that error, because your table in database didn't successfully created. Why ? Because your table hasn't got primary key (id). Add, e.g :
`_id` INT PRIMARY KEY AUTOINCREMENT,
And now every thing should work correctly
I'm making a simple database in Android. I want to add new table after my code has executed once. Now, whenever i try changing my onCreate() method in EventDataSqlHelper class my app crashes.
This is probably because onCreate() associated with SQLiteOpenHelper is executed only when app is first run and we can't make further modifications in it .
I also tried writing a separate function for adding new table. It worked perfectly on first execution.But since on 2nd exection it will overwrite its previous database, hence it causes app to crash.
Is there any way to add new tables to database if database has already been created?
package org.example.sqldemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
/** Helper to the database, manages versions and creation */
public class EventDataSQLHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
// Table name
public static final String TABLE = "events";
// Columns
public static final String TIME = "time";
public static final String TITLE = "title";
public EventDataSQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + "( " + BaseColumns._ID
+ " integer primary key autoincrement, " + TIME + " integer, "
+ TITLE + " text not null);";
Log.d("EventsData", "onCreate: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
This is what onUpgrade and DATABASE_VERSION is for.
Example:
You have a table events, and is executed on phone.
Now you decide, you want a new table users.
change DATABASE_VERSION = 2; (this is your version number)
in onCreate() , create all tables (create table events & create table users)
in onUpgrade(), create all tables that changed between version oldVersion and newVersion (create table users)
Later if you want to add new tables, increment DATABASE_VERSION again, and create all tables in onCreate, and changes in onUpgrade
You could use CREATE TABLE IF NOT EXISTS TABLENAME ... as your query, that wouldn't overwrite your existing table.