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.
Related
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();
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.
I'm new in android. I'm facing a problem creating a listview using data from sqlite database.
I found this code below to create a listview from contact data
public class Test extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a cursor with all people
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_list_item_1,
// Give the cursor to the list adatper
c,
// Map the NAME column in the people database to...
new String[] {Contacts.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
private static final String[] CONTACT_PROJECTION = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME
};
}
Now I use this code to pull data from database
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
Now How can I combine these two codes so I can show data pulled from a database in this list.
Thanks in advance.
If you want to list the data from both sources (contact and DB), I think only option you have is construct an array with return values from both sources.
List finalList = new ArrayList();
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
c.moveToFirst();
Iterate this cursor and populate the String value to finalList
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c2 = myDB.rawQuery("SELECT * FROM " + TableName , null);
startManagingCursor(c2);
c2.moveToFirst();
Iterate c2 cursor and add values to finalList.
Convert finalList to array by Iterating finalList
String[] ipArray = new String[finalList.size()];
loop through list and populate the values to ipArray.
I don't have IDE handy, so I have typed the flow.
If suppose you already have data in your cursor, you can follow code in the following tutorial
http://chetanandroidarora.wordpress.com/2011/12/18/customcursoradapter/
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.
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);