Simple Cursor Adapter problem - android

Here is my code for a simple cursor adapter.
public class CursorList extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseAdapter da = new DatabaseAdapter(this, "mydb.sqlite");
da.open();
Cursor cur = da.fetchAllRecords("Doctors", new String[]{"FirstName"});
startManagingCursor(cur);
cur.moveToFirst();
do {
Log.v("Info", cur.getString(cur.getColumnIndex("FirstName")));
} while(cur.moveToNext());
cur.moveToFirst();
String[] from = new String[]{"FirstName"};
int[] to = new int[]{R.id.row};
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);
setListAdapter(sca);
}
}
The data records are displayed correctly in the log, but the code stops working when it reaches the
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);
line.
The error I get is :
ERROR/AndroidRuntime(26746): Uncaught handler: thread main exiting due to uncaught exception
ERROR/AndroidRuntime(26746): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arnab.cursorlist/com.arnab.cursorlist.CursorList}:
java.lang.IllegalArgumentException: column '_id' does not exist
Where am I going wrong?
Why does it give an error that column '_id' doesn't exist? Is it a necessary column which we have to have in our tables?
EDIT:
When I put the cursor related code in a try catch block, something like this:
try {
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);
setListAdapter(sca);
}
catch(Exception E) {
Log.v("Error", E.getMessage());
}
I get the message :
VERBOSE/Error(1026): column '_id' does not exist
#Rasel : Here is the fetchAllRecords method
public Cursor fetchAllRecords(String table, String columns[]) {
return mDb.query(table, columns, null, null, null, null, null);
}

Why does it give an error that column '_id' doesn't exist? Is it a necessary column which we have to have in our tables?
Yes, if you want to use your database information in a cursor adapter. The adapter uses it for internal purposes. Your table must have an '_id' column, and you must select it in your query (so it is in the Cursor result set). You do not have to actually display it in your ListView.
Revised for Posterity
Instead of actually adding the '_id' column, you can SELECT your own 'id' column as '_id', and it will work just the same.

Write Cursor related code in try catch block.Your problem will be solved.Check when created table you typed different column rather than '_id'

You need to include the table _id in the projection. the list cursor adapter needs the _id to keep track of the rows. you don't have to actually display it anywhere or use it but the cursor needs to contain that column. also a primary key column named _id is mandatory in every android table.

Related

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.

Unable to show data in Gridview in Android ! please help me out

I am entering some values in to my SQLlite database and then retrieving them in a gridview.I am getting a Error "column'_id'" does not exist.but I have not used any _id named column in the database. How can I make it work?? I think theres some problem with SimpleCursor Adapter .
GridView gv = (GridView)findViewById(R.id.gridView1);
try
{
db1 = openOrCreateDatabase("record.db", Context.MODE_PRIVATE,null);
db1.execSQL("CREATE TABLE IF NOT EXISTS stu(ID INTEGER primary Key,NAME VARCHAR foriegn key,age VARCHAR);");
db1.execSQL("INSERT INTO stu VALUES (1,'mona','123');");
Cursor c = db1.rawQuery("SELECT * FROM stu", null);
if(c!= null){
if (c.moveToFirst()) {
do {
String[] cols = new String[]{c.getString(c.getColumnIndex("ID")),c.getString(c.getColumnIndex("NAME"))};
int[] views = new int[] {R.id.textView1,R.id.textView2};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
c, cols, views);
gv.setAdapter(adapter);
}while(c.moveToNext());}
}} catch(Exception e){
Toast.makeText(getBaseContext(),"errord"+ e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The documentation for CursorAdapter (which SimpleCursorAdapter extends) states:
The Cursor must include a column named "_id" or this class will not work.

Why is my ListAdapter for android not working?

I am trying to get info from a database to a listadabter.
Here is my code for getting the information to the layout:
Cursor c = mnDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] columns = new String[] {EquationsDbAdapter.KEY_VALUE};
int to[] = new int[] {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1 ,c , columns , to);
setListAdapter(adapter);
My error is given by LogCat as :java.lang.IllegalArgumentException: column '_id' does not exist
I have seen some other questions and tutorials and none of those seem to solve my problem. I don't even have a column in my database for _id.
This is because SimpleCursorAdapter needs a field returned called "_id", though it doesn't have to be an actual name of a column in your table, but could be an alias. There's a few threads here on SO talking about this, such as:
Android: column '_id' does not exist
Android column '_id' does not exist?

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);
?

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