Simple Cursor Adapter Throw Exception illegal Argument exception? - android

My Cursor
Cursor c= db.query(DBHelper.EXAM_DATA,new String [] {DBHelper.EXAM,DBHelper.FILE}, null,null, null, null, null);
Loop for the Cursor
c.moveToFirst();
do
{
name = c.getString(0);
file = c.getString(1);
Toast.makeText(this, name + " "+file ,Toast.LENGTH_LONG).show();
adapter = new SimpleCursorAdapter(this, R.layout.row_reasoning, c, new String [] {file}, new int [] {R.id.txtList});
LvReasoning.setAdapter(adapter);
}while(c.moveToNext());
Logcat Showing This Error
01-20 16:33:55.154: E/AndroidRuntime(2426): FATAL EXCEPTION: main
01-20 16:33:55.154: E/AndroidRuntime(2426): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.ListReasoning}: java.lang.IllegalArgumentException: column '_id' does not exist
My Table have _id Column but I do not know how to solve this error

c.moveToFirst();
do
{
name = c.getString(0);
file = c.getString(1);
Toast.makeText(this, name + " "+file ,Toast.LENGTH_LONG).show();
adapter = new SimpleCursorAdapter(this, R.layout.row_reasoning, c, new String [] {DBHelper.FILE}, new int [] {R.id.txtList});
}while(c.moveToNext());
LvReasoning.setAdapter(adapter);
I used this and This is Working. I have passed DBHelper table field name and its Work Fine.. But I really dont know Why that code not worked...

The cursor given to a SimpleCursorAdapter must contain a column named _id. The fact that it exists in the table is not enough, you have to select it so include it in the list of columns returned:
Cursor c= db.query(DBHelper.EXAM_DATA,new String [] {"_id", DBHelper.EXAM, DBHelper.FILE}, null,null, null, null, null);
You also only need to instantiate and set the adapter once. Move these statements outside of the while loop (you can remove the loop entirely if you don't need to toast the contents of each cursor row):
adapter = new SimpleCursorAdapter(this, R.layout.row_reasoning, c, new String [] {file}, new int [] {R.id.txtList});
LvReasoning.setAdapter(adapter);
For each cursor row, the adapter will then map the value of column 'file' to R.id.txtList within R.layout.row_reasoning.

Related

Get value of ListView item in Android

I am filling my ListView with data which I am getting from the database I created. I want to get the name of the item in ListView which is being long clicked.
I have tried using following method:
- parent.getItemAtPosition(position).toString();
- myListView.getItemAtPosition(position).toString();
- myListView.getSeletedItem(position).toString();
These three statements work well but as I am filling up the LisView by getting data from my database so I am getting the following value returned:
09-20 13:01:22.370: I/System.out(5351): android.database.sqlite.SQLiteCursor#426925b0
whereas the Item's name, which I am clicking, is 'Home'..
Please help me. How can I convert android.database.sqlite.SQLiteCursor#426925b0 into Home?
MY ADAPTER:
mCursor = mDB.fetchData();
String[] columns = new String[] { AreaDatabase.KEY_AREA };
int[] to = new int[] { R.id.tvArea };
mAdapter = new SimpleCursorAdapter(this, R.layout.lvarea, mCursor,
columns, to);
lvArea.setAdapter(mAdapter);
fetchData() function:
public Cursor fetchAreaData() {
Cursor mCursor = ourDatabase.query(AREA_TABLE_NAME, new String[] {
KEY_ROWID, KEY_AREA }, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Cursor has method getString(int columnIndex). You can use that to get String value from Cursor from specified column index.
> Cursor currentCur = myListView.getItemAtPosition(position);
> String name = currentCur.getString(1); //It will return KEY_AREA (column index 1) value from Cursor
do like this :
parent.getItemAtPosition(position).toString();

SQLite Android Logcat error for select statement

02-23 20:16:17.499: E/AndroidRuntime(25817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.makkosarka/com.example.makkosarka.Table.Table}:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.makkosarka/
com.example.makkosarka.Table.Liga1}: java.lang.IllegalArgumentException: column '_id' does not exist
and here are the methods that are trying to select records from this table and than display
in listview
private void populateListFromDB(){
Cursor cursor = myDB.getAllRows("1");
startManagingCursor(cursor);
String[] columnFromTable = new String[]
{DBadapter.KEY_HOSTID, DBadapter.GUESTID, DBadapter.KEY_HSCORE , DBadapter.KEY_GSCORE };
int[] toLayoutFild = new int[] {R.id.txtview_name, R.id.txtview_gameno, R.id.txtview_won, R.id.txtview_lost, };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, R.layout.rowlayout,
cursor, columnFromTable, toLayoutFild);
ListView mylistview = (ListView) findViewById(R.id.listview_table);
mylistview.setAdapter(myCursorAdapter);
}
This is in the Adapter class and i'm not even selecting the "_id"(KEY_ROWID) column
public static final String[] ALL_COLUMNS = new String[] {KEY_HOSTID, KEY_GUESTID,
KEY_HSCORE, KEY_GSCORE};
public Cursor getAllRows(String league) {
Cursor c = db.query(true, DUELS_TABLE, ALL_COLUMNS,
null, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
What does that error mean is it possible that the table is not created at all?
I have two tables and I`m using the same method to select records for the other one it works perfectly but for this it shows this error listed on the top of this question
This is in the Adapter class and i'm not even selecting the "_id"(KEY_ROWID) column
CursorAdapter and its subclasses require that the Cursor have a column named _id. Use your own if you have one, or else switch to rawQuery() so you can include ROWID AS _id in your list of columns to return.

ListView Data from SimpleCursorAdapter result of a query

Since a few month I am engaged with Android development and now I have a problem I dont get the right answer.
I have a ListView with data filled from a SimpleCursorAdapter. The query which should provides the results has a where statement, but it returns all records of the table.
final Cursor c = mStorage.loadList();
startManagingCursor(c);
c.moveToFirst();
final ListCursorAdapter adapter =
new ListCursorAdapterAusgabe(this, R.layout.listview,
c, FROM, TO);
adapter.setViewBinder(new ListViewBinderAusgabe());
setListAdapter(adapter);
The query:
int mode = 0;
public Cursor loadList() {
return mDb.getReadableDatabase().query(TABLE.NAME, TABLE.ALL_COLUMNS,
"mode=?", new String [] {String.valueOf(mode)}, null, null, null, null);
}
In read in this forum that there must be an _id column: In the above mentioned table there is one column with "_id". I also tried to enter "mode" in single quotations and double quotations but it didn't work. Has anybody an idea?
Thank you in advance,
Hadja
Have you tried
return mDb.getReadableDatabase().query(TABLE.NAME, TABLE.ALL_COLUMNS,
"mode=" + String.valueOf(mode), null, null, null, null, null);
?

SimpleCursorAdapter is being difficult to use

I have been stuck at one point from long time, i.e with the use of
SimpleCursorAdapter
as it fails while returning the correct value. I have seen similar many post in SO itself, saying that I should add _id column in the cursor database query, rather I should do
db.rawQuery(String,String)
My code in the onCreate(..) is
HospitalData = new Database(this);
HospitalData.open();
Cursor c = HospitalData.getAllRows_Patient_Db();
startManagingCursor(c);
c.moveToFirst();
//HERE SOME LOOP IS NEEDED FOR TRAVERSING AND PUTTING IN THE LISTVIEW
while(c.isAfterLast() == false)
{
String[] columns = new String[] { c.getString(1), c.getString(2) };
int[] to = new int[] { R.id.room_number_db, R.id.pt_initial_db };
adapter = new SimpleCursorAdapter(this,R.layout.patient_db, c,columns,to);
c.moveToNext();
}
setListAdapter(adapter);
And previously my database accessing code was as follows
public Cursor getAllRows_Patient_Db()
{
return db.query(DATABASE_PATIENT_TABLE, new String[] {KEY_ROWID, KEY_ROOM_NUMBER,
KEY_PATIENT_INITIAL
},
null,
null,
null,
null,
null);
}
where KEY_ROWID is defined as follows
public static final String KEY_ROWID = "_id";
And the error with this is
07-04 22:10:23.301: ERROR/AndroidRuntime(16795): Caused by: java.lang.IllegalArgumentException: column '90' does not exist
07-04 22:10:23.301: ERROR/AndroidRuntime(16795): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:314)
07-04 22:10:23.301: ERROR/AndroidRuntime(16795): at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:312)
Here column 90 is not the column id but according to my database is the data stored in cursor.getString(1), but I think here it is trying to search cursor.getString(0) which is the row id.
Later I changed my code as follows
public Cursor getAllRows_Patient_Db()
{
String db_sel = "SELECT id as _id, KEY_ROOM_NUMBER" +
",KEY_PATIENT_INITIAL FROM DATABASE_PATIENT_TABLE";
return db.rawQuery(db_sel,null);
}
But still I am getting error, this time error is different
07-04 21:36:12.510: ERROR/global(9861): Deprecated Thread methods are not supported.
07-04 21:36:12.950: ERROR/AndroidRuntime(9861): FATAL EXCEPTION: main
07-04 21:36:12.950: ERROR/AndroidRuntime(9861): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pro/com.pro.CopyOfFirstScreen}: android.database.sqlite.SQLiteException: no such table: DATABASE_PATIENT_TABLE: , while compiling: SELECT id as _id, KEY_ROOM_NUMBER,KEY_PATIENT_INITIAL FROM DATABASE_PATIENT_TABLE
07-04 21:36:12.950: ERROR/AndroidRuntime(9861): Caused by: android.database.sqlite.SQLiteException: no such table: DATABASE_PATIENT_TABLE: , while compiling: SELECT id as _id, KEY_ROOM_NUMBER,KEY_PATIENT_INITIAL FROM DATABASE_PATIENT_TABLE
I am stuck with it from very long time, please help!!
EDIT : Okay now with you guys help my query statement is correct and thanks for that, I am sorry I am not good in understanding the syntax for database query but I am trying to learn
The working query after changes is
String db_sel = "SELECT _id as _id, room_number" +",patient_initial FROM " + DATABASE_PATIENT_TABLE;
Actually I had to change the declared String with the key values
public static final String KEY_ROWID = "_id";
public static final String KEY_ROOM_NUMBER = "room_number";
public static final String KEY_PATIENT_INITIAL = "patient_initial";
But now I see another problem that is not from the query statement but the way I am accessing or using the simplecursorAdapter
As you can see that my table has 2 rows and 3 columns, Now I want to fetch the data from column 2 and column 3 and put it in my listview.
But after the fix from the query I am getting another error
Originally it was
String[] columns = new String[] {c.getString(1), c.getString(2) };
int[] to = new int[] { R.id.room_number_db, R.id.pt_initial_db };
adapter = new SimpleCursorAdapter(this,R.layout.patient_db, c,columns,to);
c.moveToNext();
setListAdapter(adapter);
And the error was
07-05 21:32:29.228: ERROR/AndroidRuntime(1505): Caused by: java.lang.IllegalArgumentException: column '90' does not exist
07-05 21:32:29.228: ERROR/AndroidRuntime(1505): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:314)
07-05 21:32:29.228: ERROR/AndroidRuntime(1505): at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:312)
android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:312)
As you can see it is trying to access the data of first column inspite of accessing the row
After that I made changes in my code
int x = 0;
String[] columns = new String[] { c.getString(0),c.getString(1), c.getString(2) };
int[] to = new int[] { x, R.id.room_number_db, R.id.pt_initial_db };
adapter = new SimpleCursorAdapter(this,R.layout.patient_db, c,columns,to);
c.moveToNext();
setListAdapter(adapter);
This was only a guess in order to find out how differently SimpleCursorAdapter works compared to a normal cursor and the error I get is
07-05 21:34:47.947: ERROR/AndroidRuntime(1966): Caused by: java.lang.IllegalArgumentException: column '1' does not exist
07-05 21:34:47.947: ERROR/AndroidRuntime(1966): at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:314)
I know this question is becoming too long :-( do u suggest me to remove some code from here.
The new error is saying that you don't have the table "DATABASE_PATIENT_TABLE" in your database. From your code that appears to be the Static Field name for the string that contains the name of the table in the database and not the name of the table in the database.
In the code below you need to change "DATABASE_PATIENT_TABLE" to the name of the table in the database.
String db_sel = "SELECT id as _id, KEY_ROOM_NUMBER" +
",KEY_PATIENT_INITIAL FROM DATABASE_PATIENT_TABLE";
Try this and see if it will work:
String db_sel = "SELECT id as _id, KEY_ROOM_NUMBER" +
",KEY_PATIENT_INITIAL FROM" + DATABASE_PATIENT_TABLE;
As for your original error a SimpleCursorAdapter must contain the field of _id. The change you made to the SQL Statment that powers the cursor should fix it but you need to make sure you have the right table name in the SQL statement.
Hope this helps.
Have you read this part of error stack:
android.database.sqlite.SQLiteException: no such table: DATABASE_PATIENT_TABLE:
?
You just have no such table in database. It's not CursorAdapter problem.
Your loop seems completely pointless - just read some java handbook.
Ok, lets start to list some problems in your code:
String[] columns = new String[] { c.getString(1), c.getString(2) };
columns[] should contain columns names not values...
In your while{} loop you are creating dozens(?) of SimpleCursorAdapters while only the last on is passed.
This part of code:
String db_sel = "SELECT id as _id, KEY_ROOM_NUMBER" +
",KEY_PATIENT_INITIAL FROM DATABASE_PATIENT_TABLE";
is obviously wrong. I assume that you have something like
private static String DATABASE_PATIENT_TABLE = "patient";
so just use those constants:
String db_sel = "select id as _id, +"KEY_ROOM_NUMBER+", "+ KEY_PATIENT_INITIAL +" from "+DATABASE_PATIENT_TABLE;
Replace that:
String[] columns = new String[] { c.getString(0),c.getString(1), c.getString(2) };
int[] to = new int[] { x, R.id.room_number_db, R.id.pt_initial_db };
With that:
String[] columns = new String[] { c.getColumnName(1), c.getColumnName(2) };
int[] to = new int[] {R.id.room_number_db, R.id.pt_initial_db };
The problem is fixed, the main thing is that I should make sure I always query for the _id with each query to the database, but if I do it with cursor.getString(someIndex) then this gets misleaded as the adapter in my case is taking the content of first column as the rowid and is trying to search the row.
Nether doing rawQuery(),or using "Select _id as _id" stuffs are mandatory. these things are sometime misleading as I felt.
So keeping things simple below is the code.
Database code
public Cursor getAllRows_Patient_Db()
{
return db.query(DATABASE_PATIENT_TABLE, new String[] {
KEY_ROWID,
KEY_ROOM_NUMBER,
KEY_PATIENT_INITIAL
},
null,
null,
null,
null,
null);
}
Activity Code
HospitalData = new Database(this);
HospitalData.open();
Cursor c = HospitalData.getAllRows_Patient_Db();
startManagingCursor(c);
String[] columns = new String[] {HospitalData.KEY_ROOM_NUMBER,HospitalData.KEY_PATIENT_INITIAL };
int[] to = new int[] { R.id.room_number_db, R.id.pt_initial_db };
adapter = new SimpleCursorAdapter(this,R.layout.patient_db, c,columns,to);
c.moveToNext();
setListAdapter(adapter);

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