simple cursor adapter column '_id' does not exist - android

I have _id set up in the database but when debugging it says the _id does not exist at this line:
SimpleCursorAdapter sqldb_adapter = new SimpleCursorAdapter(this, Resource.Layout.Recordslayout, sqldb_cursor, from, to);
I am using the tutorial from this blog.
One thing I do not have it set up in my mainactivity but a different one. I have set the public class to the correct activity.

This occurs when you don't have the _id column present in the projection(String[] from in your case). Adapter needs this column. Crosscheck that _id column is present and add some code if you want further help.

Related

Using SimpleCursorAdapter got IllegalArgumentException

I got a SQLite database and I would like to display data in a listView, I try it with a SimpleCursorAdapter:
contactAdapter = new SimpleCursorAdapter(this, R.layout.contact_row, cursor,
new String[] { MyDb.ACCOUNT_NAME },
new int[] { R.id.contactNameTv });
On this very line I get an
IllegalArgumentException: column '_id' does not exists.
Well, thanks JVM I just don't see what the heck should I do with that, because I don't even use _id column and this statement also wrong because I exported the database and opened with sqlite database opener and I can see the column _id in the database so it does exist.
Can somebody tell me when this error should appear and what is it trying to tell me ?
E D I T:
njzk2 pointed me right, I wasn't queried the "_id" column in my cursor getting func. Thanks.
App Crashes On Startup Due To java.lang.IllegalArgumentException: column '_id' does not exist
see the above sample which has same issue like this may be it will help you
Solution
You should add "_id" field when you create your table.
//example
"CREATE TABLE TABLE_NAME (_id INTEGER PRIMARY KEY AUTOINCREMENT,field1 TEXT, field2 TEXT, etc TEXT)";
The Cursor must include a column named "_id" or this class will not work.
Additionally, using {#link android.database.MergeCursor} with this class will not work if the merged Cursors have overlapping values in their "_id"
columns.
Warning!!
SimpleCursorAdapter this constructor was deprecated in API level 11. This option is discouraged, as it results in Cursor queries being performed on the application's UI thread and thus can cause poor responsiveness or even Application Not Responding errors. As an alternative, use LoaderManager with a CursorLoader.
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
An alternative is to use CursorAdapter and CursorLoader.
CursorAdapter is very useful when you work with databases for example if you want to show a list of data in ListView, GridView or RecyclerView directly from a database.
CursorLoader runs an asynchronous query in the background!
http://developer.android.com/reference/android/content/CursorLoader.html
I hope it helps you!!
cheers.

Populating Spinner from datasbase ina android

i m trying to display a list of sessions stored in database into a Spinner with the help of SimpleCursorAdapter. some how not able to do so
Cursor cs=db.getAllSession();
String[] from=new String[]{"sess_name"};
int[] to=new int[]{android.R.id.text1};
SimpleCursorAdapter adapter= new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cs, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
sp.setAdapter(adapter);
session table has two fields id and sess_name.
i m getting illegal argument exception.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.world.shaman/com.world.shaman.Test}: java.lang.IllegalArgumentException: column '_id' does not exist
i dont know wats the problem
As biegleux said, the cursor needs to have an _id column for the spinner to work.
This does not necessarily mean you need to change the column name in your DB. That would be the recommened way, but you could also modify your query to achieve the desired result:
SELECT id AS _id, sess_name FROM your_table
Use _id as a name of your column in your session table instead of id.
From CursorAdapter docs:
The Cursor must include a column named "_id" or this class will not
work.

Column '_id' does not exist SimpleCursorAdapter revisited

I want to use the SimpleCursorAdapter to fill in my ListActivity, but I'm getting the classic exception because there is no '_id' field in my Cursor. Unfortunately, this type of query does not provide me with a field that I can use as my _id field being of the form:
SELECT DISTINCT room from tblRates WHERE resid='ABC' AND date='2011-10-17'
Because of the DISTINCT I can't just add in the _id. So what do I do short of setting up a custom Adapter?
Btw, I have seen this post already so I do understand why I'm getting the error. Just wondering how to get an _id in there with the type of query I'm doing:
Android column '_id' does not exist?
You could do something like this...
SELECT DISTINCT room, 1 _id from tblRates WHERE resid='ABC' AND date='2011-10-17'
This will add an _id column with a value of 1 for each row. Also I think sqlite has something like a hidden "rowid" column for each table if you want distinct values for the column instead of a 1.
So what do I do short of setting up a custom Adapter?
Besides the custom Adapter approach, you could use CursorWrapper to add your own _id values. Just sequentially number them starting from 1 or something, and don't attempt to use them as actual keys in your database. :-)
UPDATE
Off the cuff...
Step #1: Create a subclass of CursorWrapper.
Step #2: Hang onto the getColumnCount() value of the wrapped Cursor, here referred to as N.
Step #3: Override getColumnCount() to return N+1.
Step #3: Override getColumnIndex() to return N as the _id column index.
Step #4: Override all other methods that take int columnIndex as a parameter. If the index is not N, delegate the work to the wrapped Cursor; otherwise, implement it yourself (or throw a RuntimeException if it is impossible or inconvenient and you don't need it). For getInt() and getLong() implementations (not sure which CursorAdapter uses), return some likely unique value (e.g., just use your position via getPosition()).
Step #5: Create an instance of your subclass, wrapping your Cursor with the DISTINCT clause, and hand that to the CursorAdapter.
Using method "query" in SQLiteDatabase may help.
For example,
SQLiteDatabase db = openHelper.getReadableDatabase();
Cursor c = db.query(
"tblRates",
new String[] { "_id", "room" },
"resid=? AND date=?",
new String[] { "ABC", "2010-10-17" },
"room",
null,
"room");
SimpleCursorAdapter a = new SimpleCursorAdapter(
getActivity(),
android.R.layout.simple_dropdown_item_1line,
c,
new String[] { "room" },
new int[] { android.R.id.text1 },
0);

Android: column '_id' does not exist

I am getting this error
IllegalArgumentException: column '_id' does not exist
When using a SimpleCursorAdapter to retrieve from my database, and the table does indeed have this _id column. Noticing this a common problem, I have tried to work around it given some of the solutions online but none of them work. This is my cursor query:
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.quoterow, myCursor, new String[]{"_id", "quote"}, new int[]{R.id.quote});
although I should mention the original did not include the _id column, I added this recently to try and solve the problem. Has anyone got any ideas that might help solve the problem?
Your database doesn't have to have a column called '_id' but the SimpleCursorAdaptor does need to have one returned. You can do this with an alias.
An example is that I have a table with columns...
uid,name,number
To query this for a SimpleCursorAdapter, I do this with a database rawQuery...
SELECT uid as _id,name,number FROM MY_TABLE
This works fine and supplies the necessary '_id' column to SimpleCursorAdapter.
EDIT: As far as I understand it the _id field is used as a unique key to make sure the data the cursor handles can be handled correctly by adapters and adapterviews etc.
Look at the data model in the docs for Content Providers.
Using a unique key in 'databases' of whatever kind is pretty much universal practice, and as far as I can tell, the use of the column name '_id' (or '_ID') is simply a way of standardizing and simplifying things across databases, content providers, cursors, adapters etc etc
In short, in order for these various components to work correctly, they need a data column with unique values but they must also 'know' what the name of that column is. They wouldn't 'know', so to speak, that my column name 'uid' is the one they need as opposed to my 'name' and 'number' columns.
You either don't have a column "_id" in your table or you are not including it in your query. That is what is causing the exception. You need to fix the following as well:
Your last argument for the CursorAdapter constructor is missing the to column reference for _id.
The int[] argument is an array of view ids to populate with values from the cursor. The String[] argument is an array of column names from a row the cursor points to.
You have to have an equal number of values in the from array as you do the to array. Because the data from the Cursor is being grabbed FROM the Cursor and placed TO the views. If there are not an equal number of values in each array, the adapter throws an exception because it doesn't have the right amount of information to map the data to the views.
Also, according to the JavaDoc for SimpleCursorAdapter, that constructor is deprecated because it causes queries to be executed in the UI thread. Which is bad. Use this one instead:
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html#SimpleCursorAdapter%28android.content.Context,%20int,%20android.database.Cursor,%20java.lang.String[],%20int[],%20int%29
A simple fix would be to add ",0" to the end of the argument list.
If you are trying to use an existing sqlite database in your Android application then you need to do some prep work to get it to work properly. This blog post describes the process in detail.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Displaying results of a SQL join in a ListActivity

I need to display results from a SQL join in a ListView/ListActivity.
I've created a cursor:
Cursor cursor = db.rawQuery(LIST_JOIN_SQL, null);
and if I iterate through the cursor, the results are exactly what I expect. However when I try and use a SimpleCursorAdapter to display these results in a ListView I get a runtime exception because there is no column called ' id'.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item, cursor, FROM, TO);
Where FROM and TO are defined as:
private static String[] FROM = { "name", };
private static int[] TO = { R.id.name, };
Now I figure I'm probably using the wrong approach here, as it seems SimpleCursorAdapters aren't meant for displaying results of joins.
What approach would you recommend here? I'm restricted to using Android 1.6 APIs.
Try selecting one of your columns as _ID alias
select col1 as _id from table
To use CursorAdapter (or any of its subclasses) you're required to have the "_id" column; it's explicitly stated in the documentation. That's because CursorAdapter uses this column heavily.
What I recommend is whatever you think (based on your project) to be the easier of these two paths:
Create an _id field in one of the tables so that when you join, you end up with an _id field.
Implement your own ListAdapter (starting from BaseAdapter) that is essentially a CursorAdapter but doesn't require an _id field.
I suspect #1 would be easier to do if you control the database, but that you'd have to do #2 if you cannot change the databases' schema.

Categories

Resources