The application crashes when inserting data from the database in an autoCompleteTextView.
I have 2 classes
First, Test class
public class Test extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
final DataBaseHelper myDb = new DataBaseHelper(this);
final String [] myData = myDb.SelectAllData();
final AutoCompleteTextView autoCom = findViewById(R.id.stations);
ArrayAdapter arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, myData);
autoCom.setAdapter(arrayAdapter);
}}
Second, DataBaseHelper class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "stations";
private static final String TABLE_STATIONS = "stations";
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public String[] SelectAllData() {
try {
String arrData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase();
String strSQL = "SELECT name FROM " + TABLE_STATIONS;
Cursor cursor = db.rawQuery(strSQL, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
arrData = new String[cursor.getCount()];
int i = 0;
do {
arrData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return arrData;
} catch (Exception e) {
return null;
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}}
The Issue
I believe that your issue is that you will encounter a table not found error as the database contains no tables. However, your are trapping the exception and taking no action as such the App will appear to not work.
If you were to add
e.printStackTrace();
before return null then the log would include something similar :-
2020-01-10 11:32:17.856 E/SQLiteLog: (1) no such table: stations
2020-01-10 11:32:17.856 W/System.err: android.database.sqlite.SQLiteException: no such table: stations (code 1 SQLITE_ERROR): , while compiling: SELECT name FROM stations
2020-01-10 11:32:17.859 W/System.err: at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
2020-01-10 11:32:17.859 W/System.err: at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
2020-01-10 11:32:17.859 W/System.err: at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
2020-01-10 11:32:17.859 W/System.err: at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
2020-01-10 11:32:17.860 W/System.err: at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
2020-01-10 11:32:17.860 W/System.err: at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
2020-01-10 11:32:17.860 W/System.err: at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
2020-01-10 11:32:17.860 W/System.err: at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1443)
2020-01-10 11:32:17.860 W/System.err: at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1382)
2020-01-10 11:32:17.860 W/System.err: at a.so59673151notable.DataBaseHelper.SelectAllData(DataBaseHelper.java:27)
2020-01-10 11:32:17.860 W/System.err: at a.so59673151notable.MainActivity.onCreate(MainActivity.java:14)
It is not a good idea to trap SQLite Exceptions as they will, in general, be serious errors and as can be seen from your own experience, confusing as you believe that the issue lie with the Array not being built.
The Fix
Part 1
You should use the onCreate method, of the DataBaseHelper class to create the stations table.
e.g.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_STATIONS + "(name TEXT);");
}
of course that may well not be the schema that you require, it is purely an example. You may wish to refer to CREATE TABLE
Part 2
As the database has been created, the DataBaseHelper's onCreate method will not run, as it only runs one when the database is created. As such you need to delete the database. When developing the easiest ways to do this is to either :-
Delete/Clear the App's data
Uninstall the App
After which you can then rerun the App.
More
To get data from the database you need to add the data to the database, as such you'd want to add a method to the DataBaseHelper class along the lines of (again the assumption is of the basic table created above) :-
public long insertStation(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name",name);
return db.insert(TABLE_STATIONS,null,cv);
}
You may wish to have a read of insert
You could then have something like the following in the Test class :-
final DataBaseHelper myDb = new DataBaseHelper(this); //<<<<< EXISTING LINE
myDb.insertStation("MyFirstStation");
myDb.insertStation("MySecondStation");
final String [] myData = myDb.SelectAllData(); //<<<<< EXISTING LINE
Note this is just for testing, it will add the same data each time the App is run, so for each run there will be 2 extra rows.
Testing
The above changes have been tested by using :-
final DataBaseHelper myDb = new DataBaseHelper(this);
myDb.insertStation("MyFirstStation");
myDb.insertStation("MySecondStation");
final String [] myData = myDb.SelectAllData();
for (String s: myData) {
Log.d("STATIONINFO","Station Name is " + s);
}
This results in (for the first run after installing the App) :-
2020-01-10 11:49:42.321 D/STATIONINFO: Station Name is MyFirstStation
2020-01-10 11:49:42.321 D/STATIONINFO: Station Name is MySecondStation
Related
I don't know what is the problem of my database, my app keep stopping after i added the data base code.
Please can you help with to fix that.
I have tried many times to figure it out but still not getting anywhere.
This is my data base code :
public class databaseOpenHelper extends SQLiteOpenHelper{
// Country table name
private static final String TABLE_NAME= "contacts";
// Country Table Columns names
private static final String KEY_ID = "id";
private static final String NAME = "Name";
private static final String PHONENO = "PhoneNo";
public databaseOpenHelper(Context context){
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(username Text primary key,password Text)");
// create the table for the first time
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
+ PHONENO + " TEXT" + ")";
myDB.execSQL(CREATE_COUNTRY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
myDB.execSQL("drop Table if exists users");
}
public Boolean isertData(String username,String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",username);
contentValues.put("password",password);
long result = myDB.insert("users",null,contentValues);
if(result == -1){
return false;
}
else {
return true;
}
}
public Boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?",new String[] {username});
if (cursor.getCount()>0){
return true;
}
else {
return false;
}
}
public Boolean checkusernamePassword(String username,String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?",new String[] {username,password});
if (cursor.getCount()>0){
return true;
}
else{
return false;
}
}
// method to add the contact
public void addcontact(ContactModel contact){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues c=new ContentValues();
c.put(NAME,contact.getName());
c.put(PHONENO,contact.getPhoneNo());
db.insert(TABLE_NAME,null,c);
db.close();
}
// method to retrieve all the contacts in List
public List<ContactModel> getAllContacts(){
List<ContactModel> list=new ArrayList<>();
String query="SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery(query,null);
if(c.moveToFirst()) {
do {
list.add(new ContactModel(c.getInt(0),c.getString(1),c.getString(2)));
} while (c.moveToNext());
}
return list;
}
// get the count of data, this will allow user
// to not add more that five contacts in database
public int count(){
int count=0;
String query="SELECT COUNT(*) FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c=db.rawQuery(query,null);
if(c.getCount()>0){
c.moveToFirst();
count=c.getInt(0);
}
c.close();
return count;
}
// Deleting single country
public void deleteContact(ContactModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
int i=db.delete(TABLE_NAME,KEY_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
}
}
And this is my logcat :
FATAL EXCEPTION: main
Process: com.example.localisation, PID: 11700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.localisation/com.example.localisation.phone}: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1047)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:654)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:62)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1485)
at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108)
at com.example.localisation.phone.onCreate(phone.java:81)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
The failure is saying that there is not a table called contacts as per
Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
Running your code and then using the errant getAllContacts method, as indicated in the log by:-
at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108)
Works.
As such it is highly likely that you have added the contacts cable after previously running the App and that this has created the database. The database persists and thus will still exist from on run to the other. As such the onCreate method will not be called, as it is only called once when the database is created.
The easy fix is to uninstall the App and rerun. However, this will delete any existing data.
If you need to keep any data then you should a) increase the version number and then b) add code to the onUpgrade method to create the new table (same code).
For example:-
a)
public databaseOpenHelper(Context context){
super(context,"Login.db",null,2 /*<<<<<<<<<< CHANGED */);
}
b)
#Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
//myDB.execSQL("drop Table if exists users");
if (i1 == 2) {
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
+ PHONENO + " TEXT" + ")";
myDB.execSQL(CREATE_COUNTRY_TABLE);
}
}
You can the see that the contacts table has been created by using App Inspection e.g.
according to the error code you uploaded i noticed this SELECT * FROM contacts which means that you don't have table named contacts in you sqlite database so i recommend you, for testing you should use sqlite browser to create database and add data to it and then use it in your android studio project. if you get any problem fearther don't hesitate to ask it in comments thanks.
I am a beginner in android development. As per my testing, I found that the app is not running because of following line in MainActivity.java.
tasklist=db.getAllTasks();
here is the main Activity code
<pre><code>
public class MainActivity extends AppCompatActivity implements DialogEndListener{
private ToDoAdapter taskAdapter;
private List<ToDoModel> tasklist;
private Databases db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Objects.requireNonNull(getSupportActionBar()).hide();
RecyclerView taskRecyclerView = findViewById(R.id.taskRecler);
taskRecyclerView.setLayoutManager(new LinearLayoutManager(this));
taskAdapter=new ToDoAdapter(db,this);
taskRecyclerView.setAdapter(taskAdapter);
tasklist =new ArrayList<>();
FloatingActionButton fab = findViewById(R.id.floatingActionButton);
db=new Databases(this);
db.openDatabse();
ItemTouchHelper itemTouchHelper=new ItemTouchHelper(new ListTouchHandler(taskAdapter));
itemTouchHelper.attachToRecyclerView(taskRecyclerView);
tasklist=db.getAllTasks();
Collections.reverse(tasklist);
taskAdapter.setTasks(tasklist);
fab.setOnClickListener(v -> NewTaskAddition.newInstance().show(getSupportFragmentManager(),NewTaskAddition.TAG));
}
#SuppressLint("NotifyDataSetChanged")
#Override
public void handleDialogClose(DialogInterface dialogInterface) {
tasklist=db.getAllTasks();
Collections.reverse(tasklist);
taskAdapter.setTasks(tasklist);
taskAdapter.notifyDataSetChanged();
}
}
</pre></code>
I think the fault must be in database code.
<pre><code>
public class Databases extends SQLiteOpenHelper {
private static final int VESRSION =1;
private static final String NAME="appDatabase";
private static final String TODO_TABLE="todoTable";
private static final String ID="todoId";
private static final String TASK="taskDesc";
private static final String STATUS="taskStatus";
private static final String CREATE_TODO_TABLE="CREATE TABLE "+ TODO_TABLE+" ( "+ID+
" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TASK +"TEXT, "+STATUS+
" INTEGER)";
private SQLiteDatabase db;
public Databases(#Nullable Context context) {
super(context, NAME, null, VESRSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TODO_TABLE); //embedded sql
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//drop existing table
db.execSQL("DROP TABLE IF EXISTS "+ TODO_TABLE);
onCreate(db);
}
public void openDatabse(){
db=this.getWritableDatabase();
}
public void insertTasks (ToDoModel tasks){
ContentValues value= new ContentValues();
value.put(TASK, tasks.getEachtask());
value.put(STATUS,0);
db.insert(TODO_TABLE,null, value);
}
public List<ToDoModel> getAllTasks(){
List<ToDoModel> taskList =new ArrayList<>();
db.beginTransaction();
try (Cursor sqlcursor = db.query(String.valueOf(Boolean.parseBoolean(TODO_TABLE)), null, null,
null, null, null,
null, null)) {
if (sqlcursor != null) {
if (sqlcursor.moveToFirst()) {
do {
ToDoModel thisTask = new ToDoModel();
thisTask.setId(sqlcursor.getInt(sqlcursor.getColumnIndex(ID)));
thisTask.setEachtask(sqlcursor.getString(sqlcursor.getColumnIndex(TASK)));
thisTask.setStatus(sqlcursor.getInt(sqlcursor.getColumnIndex(STATUS)));
taskList.add(thisTask);
} while (sqlcursor.moveToNext());
}
}
} finally {
db.endTransaction();
}
return taskList;
}
public void updateStatus(int id,int status){
ContentValues value=new ContentValues();
value.put(STATUS,status);
db.update(TODO_TABLE,value,ID+"=?",new String[]{String.valueOf(id)});
}
public void updateTask(int id,String tasks){
ContentValues value=new ContentValues();
value.put(TASK,tasks);
db.update(TODO_TABLE,value,ID+"=?",new String[]{String.valueOf(id)});
}
public void deleteTask(int id){
db.delete(TODO_TABLE,ID+"=?",new String[]{String.valueOf(id)});
}
}
</pre></code>
Can someone help me identifying the error. Thanks in advance.
You are trying to access a table called false or true as you are using String.valueOf(Boolean.parseBoolean(TODO_TABLE)) for the table name (neither table exists).
If you inspected the log then you would have seen something along the lines of :-
2021-10-09 10:49:14.468 25593-25593/a.a.so69499435manager E/SQLiteLog: (1) no such table: false
2021-10-09 10:49:14.468 25593-25593/a.a.so69499435manager D/AndroidRuntime: Shutting down VM
2021-10-09 10:49:14.471 25593-25593/a.a.so69499435manager E/AndroidRuntime: FATAL EXCEPTION: main
Process: a.a.so69499435manager, PID: 25593
java.lang.RuntimeException: Unable to start activity ComponentInfo{a.a.so69499435manager/a.a.so69499435manager.MainActivity}: android.database.sqlite.SQLiteException: no such table: false (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM false
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.database.sqlite.SQLiteException: no such table: false (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM false
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:903)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:514)
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:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1408)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1255)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1126)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1332)
at a.a.so69499435manager.Databases.getAllTasks(Databases.java:58)
i.e. the table false could not be found because you query ends up being :-
SELECT * FROM false
You may wish to have a read of https://developer.android.com/studio/debug/#systemLog (and other sections in the linked page)
I believe you should just be using :-
Cursor sqlcursor = db.query(TODO_TABLE, null, null,
null, null, null,
null, null)
However :-
Running a single SQL in a transaction has no benefit.
A Cursor will NEVER be null when returned from any SQliteDatabase method that returns a Cursor, Checking for null is useless.
Try/catch on SQLite more often than not introduces confusion. If an exception occurs then more than likely it MUST be fixed. e.g. you appear to have missed the table false not found error
while(thecursor.moveToNext) { .... } is more concise then a moveToFirst while moveToNext loop.
you should ALWAYS close a cursor when done with it (not doing so may eventually result in a crash because too many Cursors are open).
As such perhaps consider the following :-
public List<ToDoModel> getAllTasks(){
List<ToDoModel> taskList =new ArrayList<>();
Cursor sqlcursor = db.query(TODO_TABLE, null, null,
null,null,null,null,null);
while(sqlcursor.moveToNext()) {
ToDoModel thisTask = new ToDoModel();
thisTask.setId(sqlcursor.getInt(sqlcursor.getColumnIndex(ID)));
thisTask.setEachtask(sqlcursor.getString(sqlcursor.getColumnIndex(TASK)));
thisTask.setStatus(sqlcursor.getInt(sqlcursor.getColumnIndex(STATUS)));
taskList.add(thisTask);
}
sqlcursor.close();
return taskList;
}
More
You may also wish to address the fact that the table will not have a column named taskDesc but will instead have a column named taskDescTEXT as you have omitted a space between the column name and it's type.
Instead of
private static final String CREATE_TODO_TABLE="CREATE TABLE "+ TODO_TABLE+" ( "+ID+
" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TASK +"TEXT, "+STATUS+
" INTEGER)";
results in
You probably want :-
private static final String CREATE_TODO_TABLE="CREATE TABLE "+ TODO_TABLE+" ( "+ID+
" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TASK +" TEXT, "+STATUS+ //<<<<<<<<<< ADDED a space before TEXT
" INTEGER)";
results in
If you make this change (add the space). The easy way to do this is to uninstall the App and then rerun it after changing the code. However, you will lose any existing data.
If you need to retain data and apply the change and don't know how then I'd suggest asking another question.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am stuck at how do I avoid duplicate rows in Sqlite Database.I tried every possible answer on StackOverflow but none of them worked for me.I tried using unique constraint, db.insertWithOnConflict() but both of them was of no use.
Can anyone please help me to figure out my mistake?
Here is code from my Android studio:
Params.java:
public class Params {
public static final int DB_VERSION=1;
public static final String DB_NAME="PDF_NAME";
public static final String TABLE_NAME="PDF_TABLE";
public static final String KEY_ID="ID";
public static final String KEY_NAME="NAME";
public static final String KEY_PAGE="PAGE";
}
MyDbHandler.java
public class MyDbHandler extends SQLiteOpenHelper {
public static SQLiteDatabase database;
public MyDbHandler(Context context) {
super(context, Params.DB_NAME, null, Params.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create="CREATE TABLE "+Params.TABLE_NAME+"("+Params.KEY_ID+" INTEGER PRIMARY KEY,"+Params.KEY_NAME+" TEXT UNIQUE, "
+Params.KEY_PAGE+" INTEGER"+")";
db.execSQL(create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addPDF(File file)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Params.KEY_NAME,file.getName());
values.put(Params.KEY_PAGE, ViewPdf.pagenumber);
db.insertWithOnConflict(Params.TABLE_NAME,null,values,SQLiteDatabase.CONFLICT_REPLACE);
Log.d("pa","pagenumber"+file.getName() + ViewPdf.pagenumber);
Log.d("data","Inserted");
db.close();
}
public Cursor getALlfile()
{
database=this.getReadableDatabase();
String select="SELECT * FROM "+Params.TABLE_NAME;
Cursor cursor=database.rawQuery(select,null);
return cursor;
}
}
DocumentsFragment.java:
public void onItemClick(int position) {
Intent intent = new Intent(getContext(), ViewPdf.class);
intent.putExtra("Position", position);
startActivity(intent);
if (!HistoryFragment.pdfHistory.contains(pdf.get(position))) {
HistoryFragment.pdfHistory.add(0, pdf.get(position));
} else {
File newpdf = pdf.get(position);
int pos = HistoryFragment.pdfHistory.indexOf(newpdf);
HistoryFragment.pdfHistory.remove(pos);
HistoryFragment.pdfHistory.add(0, newpdf);
}
Cursor cursor=MyDbHandler.database.rawQuery("Select * from" + Params.TABLE_NAME + "where"+Params.KEY_NAME+ "=" +(pdf.get(position).getName()) ,null);
if(cursor.moveToFirst())
Toast.makeText(getContext(),"already exist", Toast.LENGTH_SHORT).show();
else{
db.addPDF(pdf.get(position));
}
I am attaching my logcat too if its of any use:
UPDATE
2021-05-08 17:54:15.181 11873-11873/com.flashxpdfreader.flash2021 E/SQLiteLog: (1) no such column: ghty.pdf
2021-05-08 17:54:15.182 11873-11873/com.flashxpdfreader.flash2021 D/AndroidRuntime: Shutting down VM
2021-05-08 17:54:15.183 11873-11873/com.flashxpdfreader.flash2021 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.flashxpdfreader.flash2021, PID: 11873
android.database.sqlite.SQLiteException: no such column: ghty.pdf (code 1 SQLITE_ERROR): , while compiling: Select * from PDF_TABLE where NAME = ghty.pdf
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1443)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1382)
at com.flashxpdfreader.flash2021.Fragment.DocumentsFragment.onItemClick(DocumentsFragment.java:156)
at com.flashxpdfreader.flash2021.RecylerAdapter$ViewHolder.lambda$new$0$RecylerAdapter$ViewHolder(RecylerAdapter.java:137)
at com.flashxpdfreader.flash2021.-$$Lambda$RecylerAdapter$ViewHolder$8a1BheGsPwqyn4c_IFEij433NiM.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7185)
at android.view.View.performClickInternal(View.java:7162)
at android.view.View.access$3500(View.java:819)
at android.view.View$PerformClick.run(View.java:27684)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Here is screenshot from my Sqlite database Browser:
You can notice that I actually have that same file name in my Database but it still says no such column.
android.database.sqlite.SQLiteException: near "fromPDF_TABLEwhereNAME": syntax error (code 1 SQLITE_ERROR): , while compiling: Select * fromPDF_TABLEwhereNAME=fhg.pdf
Currently, your sql statement is like this:
Select * fromPDF_TABLEwhereNAME=fhg.pdf
You need to add space. Your sql statement need to be like this:
Select * from PDF_TABLE where NAME = fhg.pdf
In DocumentsFragment.java, try changing the code from
Cursor cursor=MyDbHandler.database.rawQuery("Select * from" + Params.TABLE_NAME + "where"+Params.KEY_NAME+ "=" +(pdf.get(position).getName()) ,null);
To
Cursor cursor=MyDbHandler.database.rawQuery("Select * from " + Params.TABLE_NAME + " where "+Params.KEY_NAME+ " = " +(pdf.get(position).getName()) ,null);
Rather check if your cursor returns something. if the itemcount is != 0 the the pdf exists.
Cursor cursor=MyDbHandler.database.rawQuery("Select * from " + Params.TABLE_NAME + " where "+Params.KEY_NAME+ "=" +(pdf.get(position).getName()) ,null);
if(cursor.getCount() != 0)
Toast.makeText(getContext(),"already exist",Toast.LENGTH_SHORT).show();
else{
db.addPDF(pdf.get(position));
}
Note This Question is intended to be a share your knowledge, Q&A-style.
SQLite by default creates a hidden column namely rowid which will be assigned a unique 64 bit signed integer value.
However, since SQLite version 3.8.2, SQLite has supported the WITHOUT ROWID clause, which results in the rowid being omitted.
What would the result be, assuming a successful insert?
i.e. the long returned from the SQLiteDatabase insert family (insert, insertOrThrow and insertWithOnConflict) as per :-
the row ID of the newly inserted row, or -1 if an error occurred
SQLiteDatabase - insert
As SQLite version 3.8.2 or greater is only available since API 21 Lollilop, then WITHOUT ROWID can only be used from API 21 on.
(caveat Some device manufacturers include different versions of SQLite on their devices.android.database.sqlite)
Prior to API 21 coding WITHOUT ROWID would result in a syntax error, so a result would not be possible as such a table cannot exist.
Since API 21 then the result is that 0 is returned, if the insert worked else -1.
However, that is just assuming a simple case of a single table or multiple WITHOUT ROWID tables (i.e. no ROWID tables).
Adding ROWID tables into the mix, which would be the more likely scenario, then the result is as per the previous time, since the database was opened, that a result was set (as per SQLite rather than the Android SDK) or -1.
In short, the value if not -1, indicates that a row was inserted (very likely), -1 would typically indicate that the row was not inserted.
caveat if you force a rowid to be -1 (supply -1 for the rowid column directly or via an alias) then a result of -1 could be returned, even though the row was inserted.
Example
The following demonstrates the creation of a database with a single WITHOUT ROWID table, in which two rows are inserted and the result is output to the log. A subclass of SQLiteOpenHelper is used as this appears to be the more common means of accessing SQLite Database.
DBHelperNoRowid.java (Database Helper)
public class DBHelperNoRowid extends SQLiteOpenHelper {
public final static String DB = "test_norowid";
public static final int VERSION = 1;
public static final String TBL_NOROWID = "norowid";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_MYDATA = "mydata";
SQLiteDatabase mDB;
public DBHelperNoRowid(Context context) {
super(context, DB, null, VERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_norowid_table = "CREATE TABLE IF NOT EXISTS " + TBL_NOROWID + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_MYDATA + " TEXT" +
") WITHOUT ROWID"; //<<<<<<<<<<
db.execSQL(crt_norowid_table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertUsingConvenienceInsert(long not_an_id, String text) {
ContentValues cv = new ContentValues();
cv.put(COL_ID,not_an_id);
cv.put(COL_MYDATA,text);
return mDB.insert(TBL_NOROWID,null,cv);
}
}
MainActivty.java
public class MainActivity extends AppCompatActivity {
DBHelperNoRowid mDBhlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBhlpr = new DBHelperNoRowid(this);
logInsertResult(2100L,"row 1");
logInsertResult(-898765432,"row 2");
}
private void logInsertResult(long not_an_id, String text) {
Log.d("INSERTRESULT","Insertion of a row returned " + String.valueOf(
mDBhlpr.insertUsingConvenienceInsert(not_an_id,text)
));
}
}
Result
2019-01-23 17:36:04.029 24175-24175/so.uru D/INSERTRESULT: Insertion of a row returned 0
2019-01-23 17:36:04.029 24175-24175/so.uru D/INSERTRESULT: Insertion of a row returned 0
Second run
Running the above will result in the UNIQUE constraint conflict, which will be trapped by the insert method, and then -1 will be returned e.g. :-
2019-01-23 19:49:51.915 24876-24876/so.uru E/SQLiteDatabase: Error inserting _id=2100 mydata=row 1
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: norowid._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at so.uru.DBHelperNoRowid.insertUsingConvenienceInsert(DBHelperNoRowid.java:42)
at so.uru.MainActivity.logInsertResult(MainActivity.java:23)
at so.uru.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-01-23 19:49:51.916 24876-24876/so.uru D/INSERTRESULT: Insertion of a row returned -1
2019-01-23 19:49:51.918 24876-24876/so.uru E/SQLiteDatabase: Error inserting _id=-898765432 mydata=row 2
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: norowid._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at so.uru.DBHelperNoRowid.insertUsingConvenienceInsert(DBHelperNoRowid.java:42)
at so.uru.MainActivity.logInsertResult(MainActivity.java:23)
at so.uru.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-01-23 19:49:51.918 24876-24876/so.uru D/INSERTRESULT: Insertion of a row returned -1
Code used for testing a mix of rowid and without tables
Note the following is just one of the multiple permutations used for testing:-
DBHelperBoRowid.java
public class DBHelperNoRowid extends SQLiteOpenHelper {
public final static String DB = "test_norowid";
public static final int VERSION = 1;
public static final String TBL_NOROWID = "norowid";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_MYDATA = "mydata";
public static final String TBL_WITHROWID = "withrowid";
SQLiteDatabase mDB;
public DBHelperNoRowid(Context context) {
super(context, DB, null, VERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_norowid_table = "CREATE TABLE IF NOT EXISTS " + TBL_NOROWID + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_MYDATA + " TEXT" +
") WITHOUT ROWID";
db.execSQL(crt_norowid_table);
String crt_withrowid_table = "CREATE TABLE IF NOT EXISTS " + TBL_WITHROWID + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_MYDATA + " TEXT" +
")";
db.execSQL(crt_withrowid_table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertUsingConvenienceInsert(long not_an_id, String text, boolean without_rowid, boolean generate_rowid) {
ContentValues cv = new ContentValues();
String table = TBL_WITHROWID;
if (without_rowid) {
table = TBL_NOROWID;
cv.put(COL_ID,not_an_id);
} else {
if (generate_rowid) {
cv.put(COL_ID,not_an_id);
}
}
cv.put(COL_MYDATA,text);
return mDB.insert(table,null,cv);
}
public void logLastInsertId() {
Cursor csr = mDB.rawQuery("SELECT last_insert_rowid()",null);
if (csr.moveToFirst()) {
Log.d("LASTINSERTEDROWID","The Last RowID inserted was " + String.valueOf(csr.getLong(0)));
} else {
Log.d("LASTINSERTEDROWID","Ooops there does not appear to have been a row inserted");
}
}
}
MainActivity.java (as per the last permutation used)
public class MainActivity extends AppCompatActivity {
DBHelperNoRowid mDBhlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBhlpr = new DBHelperNoRowid(this);
// Insert some rows into the table that is a rowid table
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(-1,"row 1",false,true);
logInsertResult(2100L,"row 1",true,true); //<<<<<<<<<< WITHOUT
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(-898765432,"row 2",true,true); //<<<<<<<<<< WITHOUT
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(1,"row 1",false,false);
logInsertResult(-1L,"3rd row",true,true); //<<<<<<<<<< WITHOUT
}
private void logInsertResult(long no_an_id, String text, boolean without_rowid, boolean generate_rowid) {
if (without_rowid) {
Log.d("INSERTRESULT",">>>>>>>>>> WITHOUT ROWID ATTEMPT");
}
Log.d("INSERTRESULT","Insertion of a row returned " + String.valueOf(
mDBhlpr.insertUsingConvenienceInsert(no_an_id,text,without_rowid,generate_rowid)
));
mDBhlpr.logLastInsertId(); //
}
}
I am trying to save data into a database, but it seems that the onCreate method is not run. Might be this might be another problem but the logcat
12-01 01:22:41.785 19724-19724/com.example.user.timetable_test E/SQLiteLog: (1) near "null": syntax error
12-01 01:22:41.795 19724-19724/com.example.user.timetable_test E/SQLiteDatabase: Error inserting _length=1 _name=Break
android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO null(_length,_name) VALUES (?,?)
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "null": syntax error (code 1): , while compiling: INSERT INTO null(_length,_name) VALUES (?,?))
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1058)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1607)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.user.timetable_test.setup.TableDBHandler.addEntry(TableDBHandler.java:79)
at com.example.user.timetable_test.setup.SetTable$PlaceholderFragment$1.onClick(SetTable.java:227)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
The SQLite class is:
package com.example.user.timetable_test.setup;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.user.timetable_test.MiscData;
public class TableDBHandler extends SQLiteOpenHelper{
private MiscData data = MiscData.getInstance();
private static int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "Timetable.db";
private static String[] TABLE_DAY = new String[MiscData.getInstance().getDays()];
private static String COLUMN_SESSION_NUM = "_id";
private static String COLUMN_NAME = "_name";
private static String COLUMN_LENGTH = "_length";
private SQLiteDatabase db;
public TableDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
db = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase){
Log.i("SQL", "DB Created");
for(int i = 0; i < data.getDays(); i++){
TABLE_DAY[i] = data.getDay(i + data.getFirstDay());
}
for(int i = 0; i < data.getDays(); i++){
String query = "CREATE TABLE " + TABLE_DAY[i] + "(" + COLUMN_SESSION_NUM +
" INTEGER PRIMARY KEY ," + COLUMN_NAME + " TEXT," +
COLUMN_LENGTH + " INTEGER " + ");";
sqLiteDatabase.execSQL(query);
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1){
Log.i("SQL", "DB updated");
for(int j = 0; j < data.getDays(); j++){
TABLE_DAY[j] = data.getDay(j + data.getFirstDay());
sqLiteDatabase.execSQL("DROP TABLE EXISTS " + TABLE_DAY[j]);
}
onCreate(sqLiteDatabase);
}
public void addEntry(int day, String name, int length){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_LENGTH, length);
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_DAY[day], null, values);
db.close();
}
}
I am using an array to create a dynamic number of tables.
The log message in the onCreate method doesn't show up in the logcat, I checked a lot.
Calling the addEntry method:
tableDBHandler.addEntry(page, sessionSpinners[i].getSelectedItem().toString(), Integer.parseInt(lengthText[i].getText().toString()));
If I changed the DATABASE_VERSION from 1 the onUpgrade method is called, but if the version was 1 I cannot see the message from onCreat, in the logcat.
Shouldn't this class create a .db file? Because after clicking the button, and running the method, I can't see any files in the app's folder.
INSERT INTO null - the table name is null. It comes from the TABLE_DAY array you initialize in your SQLite helper onCreate(). But onCreate() is only invoked when the database file is created, not each time you open your database.
You could move the TABLE_DAY init from onCreate() to e.g. constructor.
I am using an array to create a dynamic number of tables.
If the TABLE_DAY array is really dynamic, you're in much more trouble. Consider redesigning your database schema so that the tables are static but the content can be dynamic.