Im creating this database for a converter. Its like an 2 dimensional array. If i'm not mistaking i should look something like the picture(not in same order as in the code).
Now "getData(String x, String y)" method should go to x row of the data base return the value in y column. E.g. according to the PICTURE if I call "getData("CAD", "EUR")", the method should return "0.64955".
But the app crushes.
LogCat:
07-23 06:15:10.925: E/AndroidRuntime(28756): FATAL EXCEPTION: main
07-23 06:15:10.925: E/AndroidRuntime(28756): android.database.sqlite.SQLiteException: near "table": syntax error (code 1): , while compiling: SELECT id, AUD, CAD, EUR, GBP, USD FROM table
public class database {
private Db DbHelper;
private Context ct;
private SQLiteDatabase database;
private static class Db extends SQLiteOpenHelper{
public Db(Context context) {
super(context, "db", null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String query;
query = "CREATE TABLE table (null, AUD, CAD, EUR, GBP, USD)";
db.execSQL(query);
db.execSQL("INSERT INTO AUD VALUES (AUD, 1, 1.00074, 0.65018, 0.54310, 0.90261)");
db.execSQL("INSERT INTO CAD VALUES (CAD, 0.99888, 1, 0.64955, 0.54259, 0.90177)");
db.execSQL("INSERT INTO EUR VALUES (EUR, 1.53774, 1.53910, 1, 0.83528, 1.38818)");
db.execSQL("INSERT INTO GBP VALUES (GBP, 1.84069, 1.84240, 1.19697, 1, 1.66174)");
db.execSQL("INSERT INTO USD VALUES (USD, 1.10769, 1.10872, 0.72030, 0.60170, 1)");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}}
public database(Context c){
ct = c;
}
public database open(){
DbHelper = new Db(ct);
database = DbHelper.getWritableDatabase();
return this;
}
public void close(){
DbHelper.close();
}
public double getData(String x, String y) {
// TODO Auto-generated method stub
String [] col = new String[]{"id", "AUD", "CAD", "EUR", "GBP", "USD"};
Cursor c = database.query("table", col, null, null, null, null, null);
int iRow = c.getColumnIndex(y);
String result = "";
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = c.getString(iRow);
}
return result;
}
}
You created a table named "table", but the string "table" is an SQL keyword; try changing it:
query = "CREATE TABLE my_table (null, AUD, CAD, EUR, GBP, USD)";
issues in your code.
"table" string used as tablename is a keyword. So use different name. e.g. currency_tab
As well as you cannot give column name as "null". So we e.g. currency_name
Also you need to specify datatype and constraint if any for each column.
In select query you are using one column name id, but you are not adding it the table creation. Also as per your insertion query you are not supplying any value for id field so need to make id field as Autoincrement.
so doing all the changes, your query should look something like:
query = "CREATE TABLE currency_tab (id INTEGER PRIMARY KEY AUTOINCREMENT, currency_name TEXT NOT NULL, AUD TEXT NOT NULL, CAD TEXT NOT NULL, EUR TEXT NOT NULL, GBP TEXT NOT NULL, USD TEXT NOT NULL)";
Related
I'm trying to insert data into related tables, but I've searched many forums and no option works for me, I'm just starting out with this.
The tables are the following:
Table 1:
form CREATE TABLE(
form_id int(11) PRIMARY KEY,
dateCreation date NOT NULL);
tables 2:
create table form_mvdrecinto(
id_mvdrecinto INTEGER PRIMARY KEY AUTOINCREMENT,
fk_form_id int(11) not null,
long varchar(20) not null,
FOREIGN KEY(id_formulario_fk) REFERENCES form(id_form));
In the save method is where I have the problem, specifically in the ContentValues, how the exact statement should be in my case to insert the data in both related tables.
Thank you.
The method is the convenience insert method which simplifies the construction of INSERT SQL statements based upon a ContentValues.
SQL does not allow the insertion of rows into multiple tables. So you cannot insert into both tables in a single use of the insert method. Furthermore the insertion into the form_mvdrecinto requires you to know the value of the foreign key.
First you have various problems with the SQL.
I believe that you need/want something like ():-
CREATE TABLE IF NOT EXISTS form /* TABLE NAME AFTER, NOT BEFORE THE CREATE KEYWORD/CLAUSE */(form_id int(11) PRIMARY KEY, dateCreation date NOT NULL);
CREATE TABLE IF NOT EXISTS form_mvdrecinto(
id_mvdrecinto INTEGER PRIMARY KEY AUTOINCREMENT,
fk_form_id int(11) not null,
long varchar(20) not null,
FOREIGN KEY (fk_form_id /*<<<<< MUST BE A COLUMN IN THE TABLE */) REFERENCES form(form_id /*<<<<< pretty sureyou want to reference form_id column not the non-existent id_form column*/)
);
Assuming What you would do as an example is to have a method based upon:-
void saveFormWithRelatedFormmvdrecinto(long formId, String date, String _long) {
ContentValues cv = new ContentValues();
cv.put("form_id,formId);
cv.put("date",date);
db.insert("form",null,cv);
cv.clear();
cv.put("fk_form_id",formId);
cv.put("long",_long);
db.insert("form_mvdrecinto",null,cv);
}
obviously db is an SQLiteDatabase.
due to the ForeignKey constraint the form must be inserted prior to the formmvdrecinto (or formmvdrecintos are inserted).
As the SQLiteDatabase insert Method uses INSERT OR IGNORE ...., the above could be used for an existing form, it would simply ignore inserting the duplicate form and then continue to insert the formmdvrecinto.
It appears that you may have the misconception that FOREIGN KEY builds relationships automatically. It DOES NOT (it cannot) you have to indicate the actual relationship. FOREIGN KEY is a constraint, a rule, that says that the column(s) in the table with the foreign key MUST contain a value that exists in the REFRENECED column(s) in the REFRENCED TABLE otherwise a conflict (failure) will result. INSERT OR IGNORE does not ignore such a conflict.
Demonstration
The following is a working demonstration based upon the tables above. In addition to using a known form id for the insertion of form_mvdrecinto rows (it ads 2 such rows). It also demonstrates a more precarious insertion based upon the dateCreated (if not unique then the form_mvdrecinto inserted will be an arbritary row where the datecreated is matched).
First most of the code is in the DatabaseHelper class it being :-
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
public static final String FORM_TABLE = "form";
public static final String COL_FORM_FORMID = "form_id";
public static final String COL_FORM_DATECREATION = "date_creation";
public static final String FORM_MVDRECINTO_TABLE = "form_mvdrecinto";
public static final String COL_FORMMVDRECINTO_FORMMVDRECINTO_ID = "id_mvdrecinto";
public static final String COL_FORMMVDRECINTO_FK_FORM_ID = "fk_form_id";
public static final String COL_FORMMVDRECINTO_LONG = "long";
private static volatile DatabaseHelper instance = null;
private SQLiteDatabase db;
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null, DATABASE_VERSION);
db = this.getWritableDatabase();
/* By defauly Foreign Keys are not turned no, so turn them on */
db.setForeignKeyConstraintsEnabled(true);
}
public static DatabaseHelper getInstance(Context context) {
if (instance == null) {
instance = new DatabaseHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS " + FORM_TABLE + " ("
+ COL_FORM_FORMID + " INTEGER PRIMARY KEY "
+"," + COL_FORM_DATECREATION + " date NOT NULL"
+ ");"
);
db.execSQL(
"CREATE TABLE IF NOT EXISTS " + FORM_MVDRECINTO_TABLE +"("
+ COL_FORMMVDRECINTO_FORMMVDRECINTO_ID + " INTEGER PRIMARY KEY"
+ "," + COL_FORMMVDRECINTO_FK_FORM_ID + " INTEGER NOT NULL"
+ "," + COL_FORMMVDRECINTO_LONG + " TEXT NOT NULL"
+ ", FOREIGN KEY (" + COL_FORMMVDRECINTO_FK_FORM_ID + ") REFERENCES " + FORM_TABLE + "(" + COL_FORM_FORMID + ")"
+ ");"
);
}
public long insertForm(Long id, String dateCreated) {
ContentValues cv = new ContentValues();
if (id != null && id > 0) {
cv.put(COL_FORM_FORMID,id);
}
cv.put(COL_FORM_DATECREATION,dateCreated);
return db.insert(FORM_TABLE,null,cv);
}
public long insertForm(String dateCreated) {
return insertForm(null,dateCreated);
}
public long insertFormMVDRecinto(Long id, long form_id, String _long) {
ContentValues cv = new ContentValues();
if (id != null && id > 0) {
cv.put(COL_FORMMVDRECINTO_FORMMVDRECINTO_ID,id);;
}
cv.put(COL_FORMMVDRECINTO_FK_FORM_ID,form_id);
cv.put(COL_FORMMVDRECINTO_LONG,_long);
return db.insert(FORM_MVDRECINTO_TABLE,null,cv);
}
public long insertFormMVDRecinto(long form_id, String _long) {
return insertFormMVDRecinto(null,form_id,_long);
}
#SuppressLint("Range")
public long insertFormMVDRecinto(Long id, String dateCreated, String _long) {
long rv = -1;
Cursor csr = db.query(FORM_TABLE,new String[]{COL_FORM_FORMID},COL_FORM_DATECREATION + "=?",new String[]{dateCreated},null,null,null,"1");
if (csr.moveToFirst()) {
rv = insertFormMVDRecinto(id,csr.getLong(csr.getColumnIndex(COL_FORM_FORMID)),_long);
}
return rv;
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
}
To actually demonstrate the following MainActivity is an activity which :-
Adds 3 Form rows
Adds 3 Form_mvdrecinto rows
The first two being added using the known form_id.
The last is added according to a known dateCreated value.
Tries to add a 4th Form_mdvrecinto row BUT with a dateCreated that IS NOT in any rows (due to the no row being extracted the attempt to insert a row which would result in a FK conflict is not attempted).
:-
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbhelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelper = DatabaseHelper.getInstance(this);
long f1 = dbhelper.insertForm(10L,"2021-02-10 10:21:13"); /* id will be 10 */
long f2 = dbhelper.insertForm("2021-02-10 11:13:55"); /* id will probably be 11 */
long f3 = dbhelper.insertForm(1000l,"2021-02-10 09:00:00");
long fm1 = dbhelper.insertFormMVDRecinto(f1,"Blah001");
long fm2 = dbhelper.insertFormMVDRecinto(100l,f1,"Blah002");
/* WARNING if more than 1 form with 2021-02-10 09:00:00 then could be related to any 1 */
long fm3 = dbhelper.insertFormMVDRecinto(null,"2021-02-10 09:00:00","Blah003");
/* WILL NOT INSERT as no such dateCreated value in the Form table*/
/* does not attempt to insert into the Form_mdvrecinto because the row is not found/extracted */
long fm4 = dbhelper.insertFormMVDRecinto(null,"NOT A DATE THAT WOULD EXIST","Blah004");
}
}
hello im newbie in android studio, i have 2 tables DB, first table is budaya and second sejarah. When i try insert data to tables budaya using values put its work, but when i want to insert data to table sejarah the data it doesnt show up, please help me.
here is my bad code
public class Database extends SQLiteOpenHelper{
final static String DB_NAME = "db_budaya";
public Database(Context context) {
super(context, DB_NAME, null, 8);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS budaya(_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, kategori TEXT, deskripsi TEXT, img BLOB)";
db.execSQL(sql);
String sql1 = "CREATE TABLE IF NOT EXISTS sejarah(_id INTEGER PRIMARY KEY AUTOINCREMENT, materi TEXT)";
db.execSQL(sql1);
ContentValues values = new ContentValues();
// Budaya table
values.put("_id", "1");
values.put("nama", "Suhunan Jolopong");
values.put("kategori", "Rumah Adat");
values.put("deskripsi", "Suhunan Jolopong, yaitu bentuk bangunan yang atapnya (suhunan) memanjang, sering disebut suhunan panjang atau gagajahan. Bentuk Jolopong sendiri memiliki dua bidang atap. ");
values.put("img", R.drawable.imv_rumahadat_joloponggagajahan);
db.insert("budaya", "_id", values);
ContentValues values1 = new ContentValues();
// Sejarah table
values.put("_id", "1");
values.put("materi", "Hello world");
db.insert("sejarah", "_id", values1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS budaya");
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS sejarah");
onCreate(db1);
}
}
Please help, Thanks.
You instantiate values1 as the ContentValues object to use to insert the new row in sejarah but you use values which contains the values for the table budaya.
Also there is no need to pass a value for the auto incremented column:
ContentValues values1 = new ContentValues();
values1.put("materi", "Hello world");
db.insert("sejarah", null, values1);
As of now I have only one doubt in your code. You can use below code snippet.
ContentValues values1 = new ContentValues();
// Sejarah table
// values.put("_id", "1"); // <- Comment it
values.put("materi", "Hello world");
db.insert("sejarah", "_id", values1);
Because, values.put("_id", "1"); this line may be the issue, due to you have _id INTEGER PRIMARY KEY AUTOINCREMENT So you don't have to set value implicitly.
Learning how to program in android by following a tutorial but i am trying to also update the entry in the data base though not entirely how to do so. Any help please?
package dev.edmt.todolist;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by reale on 06/10/2016.
*/
public class DbHelper extends SQLiteOpenHelper {
private static final String DB_NAME="EDMTDev";
private static final int DB_VER = 1;
public static final String DB_TABLE="Task";
public static final String DB_COLUMN = "TaskName";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format("CREATE TABLE %s (ID INTEGER PRIMARY KEY AUTOINCREMENT,%s TEXT NOT NULL);",DB_TABLE,DB_COLUMN);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = String.format("DELETE TABLE IF EXISTS %s",DB_TABLE);
db.execSQL(query);
onCreate(db);
}
public void insertNewTask(String task){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.insertWithOnConflict(DB_TABLE,null,values,SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
public void editTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.update(DB_TABLE,values,DB_COLUMN + " = " + task,null) > 0;
db.close();
}
public void deleteTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DB_TABLE,DB_COLUMN + " = ?",new String[]{task});
db.close();
}
public ArrayList<String> getTaskList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]{DB_COLUMN},null,null,null,null,null);
while(cursor.moveToNext()){
int index = cursor.getColumnIndex(DB_COLUMN);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
}
More specifically this part, cant really say i quite understand the way it works:
public void editTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.update(DB_TABLE,values,DB_COLUMN + " = " + task,null) > 0;
db.close();
}
More specifically this part, cant really say i quite understand the
way it works:
It may work, as in not fail, but as explained below it probably does nothing of any use.
The SQLiteDatabase update method is a convenient way of issuing the SQL to perform an update. It writes/creates the underlying SQl, executes it, and also returns the result (the number of rows updated).
Using your code as an example, to do the similar without using the update method you could create the SQL :-
UPDATE Task SET TaskName = 'your_value' WHERE Task = 'your_value'
Note that this is actually useless as you are effectively saying (assuming for demonstration that the value passed to the editTask method is task001); Update the task row(s) that has/have the value of task001 in the TaskName column to be changed from task001 to task001.
Note the update method uses UPDATE OR IGNORE...... so :-
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint
violation and continues processing subsequent rows of the SQL
statement as if nothing went wrong. Other rows before and after the
row that contained the constraint violation are inserted or updated
normally. No error is returned when the IGNORE conflict resolution
algorithm is used. SQL As Understood By SQLite - ON CONFLICT clause
Suggestion
Perhaps what would be more useful if say you wanted to change a row that before the update, has a value task001. Changing it say to task002.
in this case the SQL could be :-
UPDATE Task SET TaskName = 'your_new_value' WHERE Task = 'your_original_value'
Your editTask method could then be :-
public void editTask(String original_task, String new_task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,new_task);
db.update(DB_TABLE,values,DB_COLUMN + " = '" + original_task + "'" ,null) > 0;
db.close();
}
e.g. using edittask("task001","task002");
Note how the value original_task is enclosed in single quotes.
However, the recommended way, would be to utilise arguments (which would automatically be enclosed in quotes) so the above could be :-
public void editTask(String original_task, String new_task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,new_task);
String[] whereargs = new String[]{original_task};
db.update(DB_TABLE,values,DB_COLUMN + "=?",whereargs) > 0;
db.close();
}
each ? coded in the WHERECLAUSE (3rd parameter) replaced by the respective argument in the WHEREARGS (4th parameter) on a 1 by 1 basis.
Additional
In addition to creating the SQL, the update method also invokes the SQL using an appropriate means e.g. it does the equivalent of db.execSQL(your_sql) for you.
Additionally in the case of update it then does the equivalent of :-
Cursor csr = db.rawQuery("SELECT total_changes()",null);
int total_changes = 0;
if(csr.moveToFirst()) {
total_changes = csr.getInt(0);
}
return total_changes;
Hence returning the number of updated rows.
db.update method will create SQL statement according to your given parameters and execute it. You could see the db.update() method to find a better understanding.
This question already has answers here:
Android Cursor Index out of Bound Exception
(3 answers)
Closed 6 years ago.
I'm trying to retrieve data from sqlite data base but but when I call the nameData() logcat shows the exception:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
I don't understand why, any clues?
process:
public class SearchContactByName2 extends AppCompatActivity {
String dbString="",dbString2="";
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.searchcontactbynamelayout2_main);
TextView textView=(TextView)findViewById(R.id.textViewShowName);
TextView textView2=(TextView)findViewById(R.id.textView2ShowNumber);
SearchContactByName objOfSearchContactByName=new SearchContactByName();
ContactDatabase onbOfContactDatabase=new ContactDatabase(getBaseContext());
Cursor allcontact2= onbOfContactDatabase.nameData(objOfSearchContactByName.getNameForSearchTypeString);
allcontact2.moveToFirst();
do{
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}while(allcontact2.moveToNext());
Toast.makeText(getBaseContext(), "data", Toast.LENGTH_LONG).show();
}
}
database part:
public class ContactDatabase extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME="totalContact.db";
public static final String TABLE_NAME="mecontact";
public static final String NAME="name";
public static final String PHONE="phone";
public ContactDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table mecontact" +
"(id integer primary key autoincrement, name text, phone text)");
}catch(android.database.SQLException e){
System.out.println("table create nhi ho rha");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mecontact");
onCreate(db);
}
public void insertContact(String nam,String mob){
db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(NAME,nam);
contentValues.put(PHONE,mob);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public Cursor showData(){
db=this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM mecontact", null);
return res;
}
public Cursor nameData(String dataName){
db=this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM mecontact WHERE name = '"+dataName+"'", null);
return res;
}
}
try below code
if(allcontact2.moveToFirst()){
do{
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}while(allcontact2.moveToNext());}
Toast.makeText(getBaseContext(), " no data", Toast.LENGTH_LONG).show();
actually your database has no data
Cursor allcontact2= onbOfContactDatabase.nameData(objOfSearchContactByName.getNameForSearchTypeString);
if(allcontact2.size() > 0){
while(allcontact2.moveToNext()){
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}
Toast.makeText(getBaseContext(), "data", Toast.LENGTH_LONG).show();
}
Along with the answer by sush change nameData method to,
public Cursor nameData(String dataName){
db=this.getReadableDatabase();
//String dataname might contain special characters like a quote
//retreive the cursor this way
Cursor res=db.query("mecontact",new String[]{columnsYouwantToSelect},"name =?",new String[]{dataName},null,null,null);
//if you want to select all the columns in the table replace
//the second parameter with null
return res;
}
Not really answering your question, but more advice on how to prevent trouble in the future. I would suggest you change your oncreate code to this and declare your ID value in the top like you did for the others. This will make sure the database is created correctly and that in the future if changes happen you can easily get values without making typing errors. Code like this is safer to use than pure queries.
db.execSQL("CREATE TABLE "
+ TABLE_NAME
+ " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ NAME + " TEXT,"
+ PHONE + " TEXT);" );
How can I create a DB table and fill it up with some data onto application startup?I have a init_sql.sql file with create table and insert statements but only CREATE TABLE is executed so I have my table but it is empty.
init_sql.sql
CREATE TABLE IF NOT EXISTS Event (
id INTEGER PRIMARY KEY NOT NULL,
time TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
additional_info TEXT,
stage CHAR(50)
);
INSERT INTO Event (name, time, description, stage)
VALUES ('13:30 - 14:30', 'koncert Blue tone Band',
'Mladá, energická jazzfunková kapela Blue tone Band Vás pobaví a rozhýbe zaručeně každého absolventa!', 'mainStage');
I verified that this file is correct by issuing sqlite3 myDb.db < init_sql.sql, this creates the table and inserts data.
My SQLHelper looks like this
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "alumni.db";
private Context context;
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 6);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
InputStream stream = context.getResources().openRawResource(R.raw.init_sql);
try {
String sqlString = convertStreamToString(stream);
db.execSQL(sqlString);
} catch (IOException ex) {
//TODO
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Event;");
onCreate(db);
}
And I am using it inside my DAO class like new SQLiteHelper(context).getWritableDatabase();
So any ideas what could I've been doing wrong?
execSql executes a single SQL command.
When you want to execute multiple commands, you have to execute them separately.
A better idea might be to ship the precreated database with the app.
(In that case, consider using SQLiteAssetHelper.)