The infamous 'no such column _id' for SimpleCursorAdapter - android

So yeah, I've seen questions about this all over the place, and so have accordingly added an _id alias to my query as below:
SimpleCursorAdapter sca = new SimpleCursorAdapter(getActivity(),
R.layout.activity_contact_list, cursor, new String[] {
"rowid _id", DBOps.COL_CATNAME },
new int[] { R.id.contact_list }, CursorAdapter.NO_SELECTION);
I'm creating my cursor like so:
public Cursor getAllCategories() {
return mDB.query(TABLE_NAME, new String[] { "rowid _id", COL_ID,
COL_CATNAME,
COL_ICONPATH }, null, null, null, null, null);
}
mDB in the above is a SQLite database.
I've tried changing the string to rowid as _id, which also doesn't work. Also apparently there's no need to change my table structure by adding another _id column as a few others have noted, so where am I going wrong here?
Update - here's the stack trace -
Caused by: java.lang.IllegalArgumentException: column 'rowid _id' does not exist
at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:333)
at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:107)
at com.rex.bizcontacts.ContactListFragment.onCreate(ContactListFragment.java:77)

No, you're not getting the problem.
The comment you are complaining about has the right idea. rowid _id is not a valid name. You can tell that by looking at the exception.
You are welcome to try "rowid AS _id" instead of "rowid _id". I would recommend rawQuery() rather than query(), so this can be written more naturally ("SELECT rowid AS _id, ...").

Related

syntax error in "SELECT DISTINCT _id near "SELECT"

If someone knows a better way to get a rowId from text in the row, please let me know.
I've been running around in circles with this and I know it's probably something simple, but I can't figure it out. Hoping someone can tell me what I'm doing wrong. I'm getting an error running this SQLite code:
String where = "SELECT rowid, * FROM masterRecord WHERE masNameCol=" + name;
Cursor c = db.query(true, masterName, ALL_KEYS_MASTER, where, null, null, null, null, null);
The error points to the second line.
"name" is a string variable (in this case it's "Mary"). The exact error I'm getting is:
SQLiteLog: (1) near "SELECT": syntax error in "SELECT DISTINCT _id, masNameCol, masTotalTimeCol FROM masterRecord WHERE SELECT rowid, * FROM masterRecord WHERE masNameCol=Mary"
I've tried every syntax change I could find and think of, and it never changes the error. I'm just trying to get the rowId of the row so I can change a value in another column.
Use rawQuery(), not query().
You are trying to specify the entire SQL statement, which is what rawQuery() is for. query() assembles the SQL statement from pieces, and your one piece (where) is not just the WHERE clause.
Use placeholders for queries:
where = "masNameCol = ?";
whereArgs = new String[] { name };
columns = new String[] { "rowId" , /* all other column names you are interested in */ };
Cursor c = db.query("mytable", columns, where, whereArgs, null, null, null);

paging in android sqlite

How to use paging in android sqlite? any example code directly in java?
I am using
Cursor cursor = mDb.query(DATABASE_TABLE, new String[] {KEY_DATE, KEY_REPS,
KEY_WEIGHT}, null, null, null, null, KEY_DATE + "DESC", ???);
Here there is a similar question/answer Limit Records fetched in Android (Sqlite database)
Some of the suggestions there are to use LIMIT ... OFFSET in your query, or to create your custom Cursor Adaptor. I guess it depends in which level you want to do the paging.
You can use the LIMIT keyword with index and no. of rows to fetch certain records, it goes something like this:
Cursor cursor = mDb.query(DATABASE_TABLE, new String[] {KEY_DATE, KEY_REPS,
KEY_WEIGHT}, null, null, null, null, KEY_DATE + "DESC LIMIT index, No. of records to fetch", ???);
Hope this helps.

SQLite .query() method, WHERE clause is only taking double quotes strings

I have variable:
String owner="Mike";
String[] columns ={"quantity", "price","owner"}
My cursor is trying to get
Cursor findEntry = db.query("sku_table", columns, "owner="+owner, null, null, null, null);
I got an error no such column error
android.database.sqlite.SQLiteException: no such column: owner: , while compiling: SELECT quantity, price, owner, FROM sku_table WHERE owner=Mike
But if I take this query:
SELECT quantity, price, owner, FROM sku_table WHERE owner=Mike
and add "" to Mike, and tested in sqlite browsers to execute the query, I do get back the row.
The working query looks like this:
SELECT quantity, price, owner, FROM sku_table WHERE owner="Mike"
Can somebody drop some insights about how do I incorporate double quotes? Other than use \"
Thanks!
Sorry, but that is exactly the reason why you should work with what the method offers! #Leandros and #Jake are helping in the totally wrong direction! Sorry to say that...
The only solution you should use is this:
Cursor findEntry = db.query("sku_table", columns, "owner=?", new String[] { owner }, null, null, null);
ps: Yes I down voted both answers as they may work but providing a solution that shouldn't be used.
Update:
If you need more than one where condition, just add it like you would do in a normal query
Cursor findEntry = db.query("sku_table", columns, "owner=? and price=?", new String[] { owner, price }, null, null, null);
The order of the ? and the new String[] {...} elements must be the same!
Cursor findEntry = db.query("sku_table", columns, "owner='"+owner+"'", null, null, null, null);
SELECT quantity, price, owner, FROM sku_table WHERE owner='Mike' this is the correct SELECT. You forget the ' ' (single quotes)
public Cursor show_vol(String vol,String bk,String hadnu)
{
SQLiteDatabase db = this.getReadableDatabase();
String[] columns ={"hadith"};//colums name that you select
Cursor res = db.query("volume2", columns, "hadithno=?", new String[] { hadnu }, null, null, null);
//volume2 is table name and hadithno is colume name l
//select hadith from volume2 where hadithno=hadnu //working like s
1. List item
return res;
}
I know this is an old question, but you can also do it like this:
Cursor findEntry = db.query("sku_table", columns, "owner=\'"+owner+"\'", null, null, null, null);
I just did it in my app and it worked as expected.
Jake's answer was similar, but probably wouldn't work without the \ before the '
the simplest way is to use SELECT col1,col2 FROM table_name WHERE col =' something' ; just like Leandros said , my problem was the single quotes , thnx

Android column '_id' does not exists

Previously I selected everything by putting a null, but i get an error complaining that it has too many rows, so I'm trying to get a projection of the display name, contact id and phone number but getting the following error:
"column '_id' does not exist"
Here's the code:
final String[] projection = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.CONTACT_ID };
Cursor cur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
"LENGTH(" + ContactsContract.CommonDataKinds.Phone.NUMBER
+ ") >= 8 ) GROUP BY ("
+ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, null,
sortOrder);
But the error points to this line in my customadapter
super(context, layout, c, from, to);
Need help! Thanks!
Add BaseColumns._ID to your projection array.
android needs the _id column, so include your column with private key in your query.
you can rename the result column with something like this:
"select PRIMARYKEYCOLUMN as _id,BLA,BLUBB from TABLE"
See your query. You may write column_id in place of contact_id by mistake else it will not show this type error..

Help with SimpleCursorAdapter and Listview

I am stuck with SimpleCursorAdapter, I am calling my local SQLite DB and putting it into a cursor which then is passed to the SimpleCursorAdapter.
For same reason the Log Cat keeps showing this error below. I have no idea what is going on and I have been working on this for 6 hours, I didn't think SimpleCursorAdapter would be so difficult to understand.
05-28 19:47:27.524: ERROR/AndroidRuntime(9353): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nyneaxis.android.mpg/com.nyneaxis.android.mpg.userInfo}: java.lang.IllegalArgumentException: column '_id' does not exist
setArray();
rec.open();
Cursor c = rec.getAllVeh();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.userinfo, c, new String[]{c.getString(1)}, new int[]{R.id.nameTxtL});
this.setListAdapter(adapter);
rec.close();
//data adapter
public Cursor getAllVeh() {
try{
return db.query(database_table, new String[] { key_rowid, vehicle_name,
year, make, model, style, vin, plate, notes }, null, null,
null, null, null);
}finally{
}
}
Okay I have modified my code to a rawQuery and I get this error again:
05-28 22:41:48.876: ERROR/AndroidRuntime(1359): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nyneaxis.android.mpg/com.nyneaxis.android.mpg.userInfo}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
private static final String db_sel = "SELECT id as _id, vehicle_name FROM vehicle";
public Cursor getAllVeh() {
try{
return db.rawQuery(db_sel, null);
/*return db.query(database_table, new String[] { key_rowid, vehicle_name,
year, make, model, style, vin, plate, notes }, null, null,
null, null, null);*/
}finally{
}
}
See my answer to this question Android: column '_id' does not exist problem. It explains about the need for the _id column and how to alias it if your DB tables don't have a column with that name.
****EDIT:**** To alias the column in the DB which contains 'unique identifiers' you need to use db.rawQuery(...) instead of db.query(...). The db.rawQuery(...) method takes a SQL string which will allow you to alias the column name to '_id' which is required by the adapter. Example...
Cursor c = db.rawQuery("SELECT <my_unique_column_name> as _id, vehicle_name, ... FROM vehicles");
In the above, replace <my_unique_column_name> with the actual name of the column in the vehicles table which contains unique identifiers. Also, use the actual column names for any other columns that you're requesting the data for.
Well, as the error says your database table definition is missing the default _id column that SimpleCursorAdapter expects to use as the ID column. What is your database table defined as? Add the CREATE TABLE statement you are using to your question.
SimpleCursorAdapter relies on the presence of an _id column: if you don't have it then you'll get that error.
Thanks guys for all you help. I managed to do it a different way and it seems to work like a charm. If anyone has any question or suggestions let me know.
Cursor c = rec.getAllVeh();
while (c.moveToNext()) {
String vehName = c.getString(1);
vehInfo.add(vehName);
}
//put information into the addapter for listview
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, vehInfo);
//applies adapter to listview
list.setAdapter(adapter);

Categories

Resources