ListView Data from SimpleCursorAdapter result of a query - android

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

Related

CursorIndexOutOfBounds Exception: Index 0 requested, with a size of 0

I tried to read the SQLite database column and store each values in an String array. I did the following but it returned exception cursoroutofbounds. Help me figure out what I'm doing wrong?
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
String[] places = new String[c.getColumnCount()];
c.moveToNext();
for(int i=0; i<c.getColumnCount(); i++)
places[i] = c.getString(i);
return places;
}
Here :
String[] places = new String[c.getColumnCount()];
c.getColumnCount() will return count of column in row instead of number of rows in column. use c.getCount() to initialize places Array:
String[] places = new String[c.getCount()];
Or use ArrayList .
I worked out for sometime and found out the solution:
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
c.moveToFirst();
ArrayList<String> places = new ArrayList<String>();
while(!c.isAfterLast()) {
places.add(c.getString(c.getColumnIndex("place1")));
c.moveToNext();
}
c.close();
return places.toArray(new String[places.size()]);
}
You need to change your query and further processing at multiple places. Rectify your third parameter of query method to a proper where clause or keep it null. Loop through the cursor properly and add it to your String.
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
if (c.getCount() > 0) {
String[] places = new String[c.getCount()];
int i=0;
c.moveToFirst();
do {
places[i] = c.getString(c.getColumnIndex(0)));
} while (c.moveToNext());
return places;
}
c.close();
db.close();
}
First you have an issue with c = db.query("rates_table", columns, "place1", null, null, null, null);
The third parameter will result in no rows being selected.
You could use c = db.query("rates_table", columns, null, null, null, null, null); , which would return all rows.
Or you could use c = db.query("rates_table", columns, "place1 = 'myplace'", null, null, null, null);, in which case only rows that have the value myplace in the column place1 would be shown.
The best practice way is to use the 3rd and 4th parameter in conjunction where you use ? placeholders in the 3rd parm (e.g "place1=?") and corresponding args in the 4th parameter (e.g. new String[]{"myplace"}), so to replicate the previous query you could have c = db.query("rates_table", columns, "place1=?", new String[]{"myplace}, null, null, null);
Using c.moveToNext, will try to move to the next (initially the first) row of the cursor. However, if it cannot move (i.e. there are no rows, as would be the case as described above) it will not fail, rather it returns false (true if the cursor could be moved).
So You need to check this otherwise, in the case of no rows, an attempt to access a row will fail with Cursor out of bounds Index 0 requested, with a size of 0 (i.e. you requested the first (index 0) when the size of the cursors (number of rows) is 0.
There are various ways to check.
However I suspect you will then wonder why your loop only displays 1 column. That would be because you have said in the query to just get 1 column.
If you changed the query's 2nd parameter to null, it would get all columns.
At a guess you want to return an array of all places.
Assuming this then :-
// get Cursor with all rows(3rd parm null) for the place1 column (2nd parm)
c = db.query("rates_table", columns, null, null, null, null, null);
// Create String array according to the number of rows returned.
String[] places = new String[c.getCount()];
// loop through all rows setting the respective places element with the
// value obtained from the Cursor
while (c.moveToNext) {
places[c.getPosition()] = csr.getString(csr.getColumnIndex("place1"));
}
csr.close(); // Should always close a Cursor
return places;

how to retrieve the sum of column values in simplecursoradapter in sqlite database

Am using db query to sum the column values by using group by clause. I can get the total amount but i couldn't display the values in simplecursoradapter. Please help me to display the total values. I have posted my code below.
String[] columns = new String[] { KEY_ID, KEY_CATEGORY,"sum("+KEY_AMOUNT+")as" + KEY_AMOUNT,
KEY_COMMENT };
Cursor cursor = db.query(TABLENAME2, columns, null, null, null, null,
null);
return cursor;
To display the values in Listview using Simplecursoradapter
String[] from = new String[] { Dailydialog.KEY_CATEGORY,
Dailydialog.KEY_AMOUNT,Dailydialog.KEY_COMMENT};
int[] to = new int[] { R.id.id2, R.id.id3,R.id.id4};
cursorAdapter1 = new SimpleCursorAdapter(this, R.layout.dailydialogall, cursor1,
from, to);
listview_dialog.setAdapter(cursorAdapter1);
Total values are not listed in Listview.
Instead of "sum("+KEY_AMOUNT+")as" + KEY_AMOUNT use " sum("+KEY_AMOUNT+") as " + KEY_AMOUNT. Notice the spaces? Its always a good idea to print your query in log. Another thing is that you need to specify group by clause as well for sum function otherwise only one row will be returned with total sum of amount of all the rows.

Android Simplecursoradapter not using the cursor i'm passiing

cursor = getContentResolver().query(GroceryItemProvider.ITEM_URI, projection, id+"="+GroceryItemTable.LIST_ID, null, null);
adapter= new SimpleCursorAdapter(this, R.layout.list_row, cursor, from, to , 0);
adapter.swapCursor(cursor);
This creates a list with the entire table rather than the cursor I pass with custom values, is that the default behaviour??
Do you mean you are getting all columns of data or all rows of data? If you are getting all columns, then please mention the value of variable projection. If you are getting all rows, then you can limit rows by providing the last argument to getContentResolver().query() method like:-
cursor = getContentResolver().query(GroceryItemProvider.ITEM_URI, projection, id+"="+GroceryItemTable.LIST_ID, null, "id limit 10");

How to use limit and offset to page through the data

I am new to SQLite and I don't know how to use limit and offset to select a limit number of data from the database, I mean I know the query phrase, but how to use it in a cursor so I can get those data into a listview?
Currently I am using the code below to query data from the database and show them in a listview but it seems I query too much data for one query and the SQLite fail to grow, so I want to split the query into some smaller ones and do it in one time,someone suggested me to try limit and offset,but I googled it there are really not much about it on the Internet.
Would somebody kindly provide me the guide to this? an example or a tutoral, anything will do,thx
channellist = (ListView) findViewById(R.id.Channel);
mDB = new ChannelDB(this);
String[] columns = {mDB.KEY_ID, mDB.KEY_POSTER, mDB.KEY_CHANNEL, mDB.KEY_PATH, mDB.KEY_DBLINK};
String table = mDB.channelS_TABLE;
c = mDB.getHandle().query(table, columns, null, null, null, null, null);
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.channelview,
c,
new String[] {mDB.KEY_POSTER, mDB.KEY_CHANNEL, mDB.KEY_DBLINK},
new int[] {R.id.poster, R.id.channel, R.id.douban});
adapter.setViewBinder(new ChannelViewBinder(this));
channellist.setAdapter(adapter);
pass the last argument with number as string like you need fetch 10 then you can do like this way
c = mDB.getHandle().query(table, columns, null, null, null, null, null,"10");
for more reference see How to use the LIMIT argument in an SQLite Query with Android

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