android sql cursor error - android

Im playing with sql in android and found this issue:
Im reading data from my database:
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
SingleAppModel singleAppModel = new SingleAppModel();
and when I try to get cursor.getInt(3) over here:
try {
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
singleAppModel.setId(cursor.getInt(0));
singleAppModel.setAppName(cursor.getString(1));
singleAppModel.setPackageName(cursor.getString(2));
singleAppModel.setState(cursor.getInt(3) == 1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
db.close();
It returns error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
Weird is that if I delete line where Im calling cursor.getInt(3), it works.
Colum with that value exists and Im sure its of type INTEGER.
Also the value of cursor.getColumnCount() is 4 and value of cursor.getCount() is 1 ... so there are definetly some data...
Any advice?
Thankyou.

Rather than using * I suggest you to use,
cursor = db.rawQuery("SELECT COL0, COL1, COL2, COL3 FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
Use the appropriate values for COL0, COL1, COL2, COL3 according to your table.
That way you make sure that the order of the columns fetched in the query.
But according to this,
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
I need more information to confirm, can you add your table schema, according to the issue there is no 3rd column in the database raw.
Edit:
This can be a small programmer mistake,
Look out for the onCreate and onUpgrade methods in SQLiteOpenHelper implementation

Related

Insert if not exists: SQLite

I want to insert data if that headline doesn't exist yet in the database.
This is the error I'm getting for the written query:
near "with": syntax error (code 1): , while compiling: SELECT * FROM movie WHERE headline=Albert Collen
Code:
public boolean Insert(Item item) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline=" + item.getName() , null);
if (cursor.moveToFirst()) {
} else {
contentValues.put("name", item.getName());
long result = sqLiteDatabase.insert(TABLE, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
cursor.close();
sqLiteDatabase.close();
return true;
}
You should use query parameters
rawQuery("SELECT * FROM movie WHERE headline = ?", new String[] {"Albert Collen"});
to avoid having to escape quotes and other chars.
First of all, result query is wrong. All the string constants are to be quoted, like this
SELECT * FROM movie WHERE headline='Albert Collen';
So, try to compose query like this, perhaps it will help
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline='" + item.getName() + "'" , null);
But concatenating a query is not a good idea because it makes at least SQL-injections possible.
For example, it can cause problems when item.getName() contains following line "'; drop table movies;"
Better option would be using bind query variables. Unfortunately, I'm not familiar with how to use java-android with sqlite, so it is better for you to check how to use such a queries in android

SQLite Statement in Android Studio 3.5.3

I'm a newbie with Android Studio so please be patient... This forum often leads me with suggestions and examples (as a reader), but today I decided to ask for help:
Since hours, I try to build an SQLite statement in Android Studio: There is a column COLUMN_LAST_ATTEMPT with date and time as String, e.g. 2020-01-09 17:23, see screenshot, and I want to get the newest date (without time) from the table, e.g. 2020-09-01. I tried various options but I can't get it to run.
What I need is an Android SQLite Statement for
SELECT MAX(SUBSTR(last_attempt,11,20)) FROM quiz_questions
(which runs on DBBrowser), where 'last attempt' is a column of table 'quiz_questions', screenshot of that column in table 'quiz_questions'
I tried the following rawQueries, none of them works:
In QuizDBHelper-Class
//...
final QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
//...
public String newestQuiz(){
db = getReadableDatabase();
String result = null;
Cursor cursor = db.rawQuery("SELECT MAX(" + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT + ") FROM "
+ QuizContract.QuestionsTable.TABLE_NAME, null);
//Cursor cursor = db.rawQuery("SELECT MAX(SUBSTR(" + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT +
// ",11,20)) FROM " + QuizContract.QuestionsTable.TABLE_NAME, null);
//Cursor cursor = db.rawQuery("SELECT " + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT + " FROM " +
// QuizContract.QuestionsTable.TABLE_NAME, null);
if(cursor.moveToFirst()){
do {
result = cursor.getString(c.getColumnIndex(QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT));
} while (cursor.moveToNext());
}
cursor.close();
return result;
}
In Statistics-Class
String LastUse = dbHelper.newestQuiz();
LastUsage.setText("Letzte Challenge: " + LastUse);
//LastUsage is a TextView in activity_Statistics.xml
//attached with LastUsage = findViewById(R.id.text_lastUsage);
Either the SQLite statements are totally wrong or I make (basic?) mistakes in statistics class. I need ...newbie help!
I need something like Select column from table where substring of date-Entry == newest
Your issue appear to be column names. That is a Cursor only contains the columns extracted, not all the columns from the table. Although you are basing your query on the column as per QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT that will not be the column name in the cursor.
Rather it will will MAX(SUBSTR(" + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT +
// ",11,20))
The simplest way of managing this is to give the column in the Cursor a specific name using AS. As such perhaps use :-
Cursor cursor = db.rawQuery("SELECT MAX(" + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT + ") AS " + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT + " FROM "
+ QuizContract.QuestionsTable.TABLE_NAME, null);
However, you may prefere to use a column name (AS ????) specififc to the situation e.g.
........ AS max_" + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT + ........
You would then have to use :-
result = cursor.getString(c.getColumnIndex("max_" + QuizContract.QuestionsTable.COLUMN_LAST_ATTEMPT));
Alternately, as it's just a single value/column that is returned in the cursor you could use the column offset of 0, in which case the column name is irrelevant as long as it is valid. However, using offsets is not typically recommended due to the lack of validation of the column being accessed.
re the comment :-
I just need the date part
As the date is a recognised DateTime format (and also that such formats are directly sortable/orderable), use max(date(column_name)) or even max(column_name).

Retrieving specific table items from sqlite database

I have a SQLite database that I am trying to query in order to find all the items of a specific type. Here is the function that I am calling in order to query my database:
Cursor c = dbi.DBGrabTable("LEGS",ExerciseListActivity.this);
Here is the function definition:
public Cursor DBGrabTable(String type, Context ctx){
String query="SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type=" + type;
DBContract.DBHelper mDBHelper = new DBContract.DBHelper(ctx);
SQLiteDatabase rdb = mDBHelper.getReadableDatabase();
Cursor c = rdb.rawQuery(query,null);
if (c != null)
return c;
else
return null;
}
The error that I am getting is as follows:
android.database.sqlite.SQLiteException: no such column: LEGS (code 1): , while compiling: SELECT * FROM Exercises WHERE Type=LEGS
Therefore I am thinking it has something to do with the SQL query. I am unsure why it is saying "no such column: LEGS" I am trying to query my database to look in my Table named "Exercises" under the column header "Type" and select all the items that have the word LEGS in that column.
Can anyone see what I am doing wrong? A huge thanks in advance!
1 - Check the table definition whether the column and table name available.
2 - If table and column is available and type is text please change your sql query and try it.
String query="SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type=" + "'" + type + "'";
Use this query and make sure in maintenace of space and inverted comma. Check your Column name(Type) in TABLE_EXERCISES.
"SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type = '" + columnValue + "'";
move the cursor till last row of table.
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
} while (cursor.moveToNext());
}
}

Update doesn't work sqlite android

Having problem updating a column in a table. I tried both of these solutions:
this.openDataBase();
String SQLStatement = "update " + TABLE_POSES;
SQLStatement += " set " + COLUMN_SKIP + "=" + SKIP + " Where ";
SQLStatement += COLUMN_ID + "=" + String.valueOf(skipPoseId);
myDataBase.rawQuery(SQLStatement, null);
this.close();
and this:
this.openDataBase();
ContentValues args = new ContentValues();
args.put(COLUMN_SKIP,SKIP);
myDataBase.update(TABLE_POSES, args, COLUMN_ID + "=" + String.valueOf(skipPoseId),null);
this.close();
Neither of these code snippets work and I am not getting any exceptions thrown. What am I doing wrong?
You should use the second method using update() and you should check the return value. If the value is zero, then the state of the database isn't what you expect and no rows were updated. If the row is not zero then the updating is succeeding.
If anything is wrong with your accessing the database an exception will be thrown before the update() call.
I would take advantage of the args parameter of update() like so:
myDataBase.update(TABLE_POSES, args, COLUMN_ID + " = ?", new String[]{ Long.toString(skipPoseId) });
Use update like this,
String query="UPDATE tablename SET columnname="+var+ "where columnid="+var2;
sqlitedb.execSQL(query);
Just write your update query in String query and execute.
if you use db.begintransaction() in your code you must call db.setTransactionSuccessful() before db.endtransaction() such as:
try {
SQLHelper dbHelper = new SQLHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
...................
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
catch (Exception ex){
}
I had the exactly same issue. After much thought and debugging I saw that the WHERE condition wasn't addressing any rows of the table.
The odd thing is that the myDatabase.update command giving 1 as the return and I was understanding it as 1 row affected by the update.

Android sqlite data insertion issue

i have created a database with the table name tbl_customer and tbl_product...i can view the tbl_customer values but can't see tbl_product values.. I use adb shell to confirm my insertion. Can any one plz help me to figure out the issue
private void addProFromDB() {
// TODO Auto-generated method stub
ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase sampleDB = null;
try {
list = (ListView)findViewById(android.R.id.list);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, 1, null);
sampleDB.execSQL("create table tbl_product("
+ "pro_id integer PRIMARY KEY autoincrement,"
+ "pro_name text," + "pro_price integer);");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('1','Milk','60');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('2','Sugar','70');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('3','Oil','200');");
Cursor c = sampleDB.query(SAMPLE_TABLE_NAMES, null, null, null, null, null,
null);
char pro_nameColumnIndex = (char) c.getColumnIndexOrThrow("pro_name");
int pro_priceColumnIndex = (int) c.getColumnIndexOrThrow("pro_price");
} finally {
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAMES);
sampleDB.close();
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, new ArrayList()));
new AddStringTask().execute();
}
Also help me how i can get its primary key and display the selected value...
Best regards....
First, it is a good idea to consider using the insert() method on SQLiteDatabase, instead of executing INSERT statements via execSQL(), particularly if you do not have much SQL experience.
Second, normally, an INSERT statement lists the columns to be inserted into, which you are not doing. SQLite might support your syntax, but it makes for more fragile code.
Third, with an autoincrement column, you do not assign your own values, as you are trying to do.
Fourth, you are putting string values into integer columns. SQLite supports that, but not by actually converting the values to integers, but rather storing the strings themselves in the columns, which may not be what you want.
Fifth, getColumnIndexOrThrow() returns an int, not a char.
Sixth, you are deleting your data from the table milliseconds after inserting it, in your finally block, assuming that SAMPLE_TABLE_NAMES is set to tbl_product. If those values are not equal, then you are inserting into and querying from a table that does not exist.
Seventh, your Cursor is dead as soon as you close() the database in your finally block.
Some combination of those probably explains "the issue".

Categories

Resources