How to check if data queried from android sqlite database is empty in a bindView method?
This is what I have done so far, but I think I am doing the wrong thing.
UPDATE
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
SQLiteDatabase db;
db = openOrCreateDatabase(
"no.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
//CREATE TABLES AND INSERT MESSAGES INTO THE TABLES
String CREATE_TABLE_NOTICES = "CREATE TABLE IF NOT EXISTS notices ("
+ "ID INTEGER primary key AUTOINCREMENT,"
+ "NOT TEXT,"
+ "DA TEXT)";
db.execSQL(CREATE_TABLE_NOTICES);
Cursor myCur = null;
// SQLiteDatabase db;
myCur = db.rawQuery("SELECT ID as _id,NOT,DA FROM notices order by ID desc", null);
mListAdapter = new MyAdapter(Page.this, myCur);
setListAdapter(mListAdapter);
}
#Override
public void bindView(View view, Context context, Cursor myCur) {
TextView firstLine=(TextView)view.findViewById(R.id.firstLine);
if(myCur==null){
String message="No Message";
firstLine.setText(message);
}
}
The keyword NOT is a reserved word in MySQL. I'd be very surprised if it's not a reserved word in SQLite.
I think the problem is here:
SELECT ID as _id,NOT,DA FROM notices order by ID desc
-- ^^^
It looks like the reserved word NOT is being used as a column name. To use that as an identifier, it will need to be "escaped", by enclosing it in backtick characters.
SELECT ID as _id,`NOT`,DA FROM notices ORDER BY ID DESC
-- ^ ^
That's the normative pattern in MySQL. For SQLite, you use the (MySQL compatible ) backtick characters, or you can use double quotes (more ANSI standard compliant.)
It's also possible to qualify the column name. (I'm certain this works in MySQL).
SELECT n.ID AS `_id`, n.NOT, n.DA FROM notices n ORDER BY n.id DESC
-- ^^ ^^ ^^ ^ ^^
References:
MySQL Reference Manual: 9.3 Keywords and Reserved Words https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Certain keywords, such as SELECT, DELETE, or BIGINT, are reserved and require special treatment for use as identifiers such as table and column names.
SQLite: SQLite Keywords https://www.sqlite.org/lang_keywords.html
If you want to use a keyword as a name, you need to quote it. There are four ways of quoting keywords in SQLite:
It may also be a problem in the CREATE TABLE statement. Since you are creating the table, you have the option of using a different name for the column, a name which is not a reserved word.
Related
I have got the error message " or expected, got 'Index'" when I was trying to create a table and I do not really understand why is the code expecting a column definition or table constraint at this line
I have tried with changing the whitespaces, however that only change the place where the error is prompted. The content of the error message does not change
This is the part that I have declared the strings
public class TaskEntry implements BaseColumns {
public static final String TABLE = "Users";
public static final String INDEX = "Index";
public static final String COL_TASK_TITLE = "title";
}
The following is my code for the creating table part
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + Item_contract.TaskEntry.TABLE + " ( " +
Item_contract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
Item_contract.TaskEntry.INDEX + " INTEGER NOT NULL, " +
Item_contract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL" + ");";
db.execSQL(createTable);
}
You cannot use INDEX as a column name as it is a keyword.
The SQL standard specifies a large number of keywords which may not be
used as the names of tables, indices, columns, databases, user-defined
functions, collations, virtual table modules, or any other named
object. The list of keywords is so long that few people can remember
them all. For most SQL code, your safest bet is to never use any
English language word as the name of a user-defined object.
SQL As Understood By SQLite - SQLite Keywords
So change
public static final String INDEX = "Index";
perhaps to
public static final String INDEX = "IX";
You could enclose the column name if you really wanted it to be INDEX e.g.
public static final String INDEX = "[Index]";
As per :-
If you want to use a keyword as a name, you need to quote it. There are four ways of quoting keywords in SQLite:
'keyword' A keyword in single quotes is a string literal.
"keyword" A keyword in double-quotes is an identifier.
[keyword] A keyword enclosed in square brackets is an identifier. This is not standard SQL. This quoting mechanism is used by MS Access and SQL Server and is included in SQLite for compatibility.
`keyword` A keyword enclosed in grave accents (ASCII code 96) is an identifier. This is not standard SQL. This quoting mechanism is used by MySQL and is included in SQLite for compatibility.
SQL As Understood By SQLite - SQLite Keywords
Note
You will have to do one of the following to get the onCreate method to run and thus alter the schema:-
Delete the App's data.
Uninstall the App.
On devices with modified android versions i get this error. For example on Xiaomi devices.
String query = "select * from dialogues where userId = ? and topChat = 0 order by updatedAtByClient desc";
Cursor dialogRes = db.rawQuery(query, new String[]{userId});
Here i get exception:
android.database.sqlite.SQLiteException: no such column: topChat (code 1):,
while compiling: select * from dialogues where userId = ? and topChat = 0
order by updatedAtByClient desc
I have written the exception message by hand, because the user has sent me it in a screenshot, so there might be typos.
How can this be fixed, and why does this happen?
UPD1:
the create table statement looks similar to this:
"CREATE TABLE IF NOT EXISTS dialogues(fieldName VARCHAR, camelCaseFieldName VARCHAR,
topChat INTEGER, createdAt DATE);";
And i have a correctly implemented update method for when im changing the DB structure, but this particular table and field name did not change for a long time.
UPD2:
i have made an apk for the user with problems, that logs that table columns, and i did see the problematic column in the log, and user says that this version works ok.
So seems that this error does not happen 100% of times. Very strange. Maybe there is a way to check the database for integrity after creating it, and recreate tables with errors?
I don't believe this would be a xiaomi issue. it rather seems be the result of an unfortunate migration, where a new column had not been added and subsequently, the user might still work with the previous version of the table. and there is no other logical explanation for an absent column), simply because either the CREATE TABLE statement works - or it doesn't.
one can still work around it with ALTER TABLE. eg. when that SQLiteException occurs, addColumnIfNotExists("dialogues", "topChat", "INTEGER DEFAULT 0"); ...in order not to cause data-loss by dropping the table, only because it lacks some column.
public void addColumnIfNotExists(String tableName, String columnName, String dataType) {
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName, null);
if(! Arrays.asList(cursor.getColumnNames()).contains(columnName)) {
db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s %s", tableName, columnName, dataType));
}
} finally {
if(cursor != null) {
cursor.close();
}
}
}
I have an application, where I am detecting the type of a particular column at run-time, on page load. Please refer the below code:
public String fncCheckColumnType(String strColumnName){
db = this.getWritableDatabase();
String strColumnType = "";
Cursor typeCursor = db.rawQuery("SELECT typeof (" + strColumnName +") from tblUsers, null);
typeCursor.moveToFirst();
strColumnType = typeCursor.getString(0);
return strColumnType;
}
The above method simply detects the type of column with column Name 'strColumnName'. I am getting the type of column in this case.
Now, I want to change the column type to TEXT if I am receiving INTEGER as the column type. For this, I tried the below code:
public String fncChangeColumnType(String strColumnName){
db = this.getWritableDatabase();
String newType = "";
Cursor changeCursor = db.rawQuery("ALTER TABLE tblUsers MODIFY COLUMN " + strColumnName + " TEXT", null);
if (changeCursor != null && changeCursor.moveToFirst()){
newType = changeCursor.getString(0);
}
return newType;
}
But while executing the 'fncChangeColumnType' method, I am getting this error, android.database.sqlite.SQLiteException: near "MODIFY": syntax error (code 1): , while compiling: ALTER TABLE tblUsers MODIFY COLUMN UserID TEXT
NOTE: I also replaced 'MODIFY' with 'ALTER', but still getting the same error.
Please check if this is the right method to change the type dynamically.
Please respond back if someone has a solution to this.
Thanks in advance.
In brief, the solution could be :-
Do nothing (i.e. take advantage of SQLite's flexibility)
you could utilise CAST e.g. CAST(mycolumn AS TEXT) (as used below)
Create a new table to replace the old table.
Explanations.
With SQLite there are limitations on what can be altered. In short you cannot change a column. Alter only allows you to either rename a table or to add a column. As per :-
SQL As Understood By SQLite - ALTER TABLE
However, with the exception of a column that is an alias of the rowid column
one defined with ?? INTEGER PRIMARY KEY or ?? INTEGER PRIMARY KEY AUTOINCREMENT or ?? INTEGER ... PRIMARY KEY(??) (where ?? represents a valid column name)
you can store any type of value in any type of column. e.g. consider the following (which stores an INTEGER, a REAL, a TEXT, a date that ends up being TEXT and a BLOB) :-
CREATE TABLE IF NOT EXISTS example1_table (col1 BLOB);
INSERT INTO example1_table VALUES (1),(5.678),('fred'),(date('now')),(x'ffeeddccbbaa998877665544332211');
SELECT *, typeof(col1) FROM example1_table;
The result is :-
As such is there a need to change the column type at all?
If the above is insufficient then your only option is to create a new table with the new column definitions, populate it if required from the original table, and to then replace the original table with the new table ( a) drop original and b)rename new or a) rename original, b) rename new and c) drop original)
e.g. :-
DROP TABLE IF EXISTS original;
CREATE TABLE IF NOT EXISTS original (mycolumn INTEGER);
INSERT INTO original VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(0);
-- The original table now exists and is populated
CREATE TABLE IF NOT EXISTS newtable (mycolumn TEXT);
INSERT INTO newtable SELECT CAST(mycolumn AS TEXT) FROM original;
ALTER TABLE original RENAME TO old_original;
ALTER TABLE newtable RENAME TO original;
DROP TABLE IF EXISTS old_original;
SELECT *,typeof(mycolumn) FROM original;
The result being :-
i think the sql query statement is wrong ,try
ALTER TABLE tblUsers MODIFY COLUMN id TYPE integer USING (id::integer);
instead of id use column name....
hope this helps....
EDIT:
"ALTER TABLE tblUsers MODIFY COLUMN "+strColumnName+" TYPE integer USING ("+strColumnName+"::integer);"
I'm developing and app, which has to store elements from an ftp server to a local sqlite database on an Android device and display the elements after a search. It's been done and it's working.
Now i want to add a search method that is not case sensitive. For instance if there are apples with names such as Red apple, yellow Apple, GreeN APPle... etc. they should all be displayed when searching with keyword apple or Apple or APPle. So far i've tried to make the search argument to lower or upper case, but it doesn't work when you throw in a random generated string. Is there a way to bring this functionallity wihtout proccessing outside of the database and if so, how?
This is the source for creating the table:
private static final String DATABASE_CREATE_ITEMTABLE =
"create table ItemTable(itemId text primary key, itemName text, itemGroup text);";
This is the source for the query:
private Cursor execQueryLike(String name) {
name = "%" + name + "%";
return database.query(DB_TABLE_ITEM, columnsitemTable, column
+ " LIKE ? ", new String[] { name }, null, null, KEY_COLUMN_ITEM_NAME, null);
Don't immediately flag me for a duplicate question. My issue is different because I have a correctly formatted SQL query.
public static final String TABLE_NAME = "log";
public static final String COLUMN_ID = "_id";
public static final String LOG_TEXT = "logtext";
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " integer primary key autoincrement, " +
LOG_TEXT + " TEXT not null);";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
and I query here
String[] columns = {LOG_TEXT,COLUMN_ID};
Cursor cursor = helper.getReadableDatabase().query(TABLE_NAME, columns, null, null, null, null, COLUMN_ID + " desc");
and I catch this the exception generated containing the sql query.
catch(Exception e){
Log.D("sql Exception",e.getMessage());}
and it returns
no such column: _id: , while compiling: SELECT logtext, _id FROM log ORDER BY _id desc
I'm familar with Oracle SQL and relational databases in general. Is it my ORDER BY clause? I was certain you can ALWAYS use order by. It doesn't have the same behavior as GROUP BY.
Any ideas on why the exception?
Incase anyone wants to see i'm updating with my ArrayAdaptor statements. I'm using the cursor in a listview
String[] data = query();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, data);
listView.setAdapter(adapter);}
Rewrite
Whenever you change the schema in TABLE_CREATE you must inform you app of these changes, they will not happen automatically when you change TABLE_CREATE. The easiest way to do this is to increment your database_version in your extended SQLiteOpenHelper class. You discovered you can also uninstall / reinstall the app, for the same results. If you are savvy with SQL you could ALTER the table. But whatever the method you must make sure that you app makes the schema changes before trying to access the new columns...
Also for SQLite:
_id integer primary key
is synonymous with:
_id integer primary key autoincrement not null
And queries use descending as the default order, so ORDER BY _id is the same as ORDER BY _id DESC.
Had the same problem, meaning it should have worked but didn't (had some typos in the create command that I fixed but that still didn't help). A colleague then told me to try clearing the data (just at AppInfo and then "Clear Data") which solved my problem, apparently the old database (that didn't work) was still there and had to be cleared out first.
I just put this answer here in case anybody else like me (android beginner) stumbles across this problem, because I went through dozens of stackoverflow threads with this problem but not one offered this possibility/solution and it bothered me for quite some time.
Did you add the definition of the _id column to your create statement later on, i.e. after the code had already been run once? Databases are persisted files, so if you modify the table structure in your code you need to make sure you clear your application's data so the database file can ge re-created with the correct table/column data.