I am working on Android and my intention is to filter out my cursor. The cursor is coming from database and it has some rows. Now I want to skip some rows from cursor by using id column and pass the remaining rows to the listview adapter as cursor.
My code is like checking that the row id is equal to the filtercursor row id then have to skip the row from the presentcursor.
The code:
Cursor c = getActivity().getContentResolver().query(
Provider.CONTENT_URI_DINERS, null,
DinerColumns.COL_RESERVATION_FROM , null, null);
c.moveToFirst();
do{
String dinerId = c.getString(c.getColumnIndex(DinerColumns.COL_DIN_ID));
if(isSeatedDiner(dinerId)){
}
}while(c.moveToNext());
private boolean isSeatedDiner(String dinerID){
Cursor cursor = getActivity().getContentResolver().query(
Provider.CONTENT_URI_SEATED,
new String[] {"COUNT(*)" },SeatedDinerColumns.COL_DINE_ID +"="+dinerID , null,
null);
if(cursor.moveToFirst()){
do
{
String newId = cursor.getString(cursor.getColumnIndex(SeatedDinerColumns.COL_DINE_ID));
if(Integer.parseInt(dinerID)==Integer.parseInt(newId))
{
return true;
}
}while(cursor.moveToNext());
}
return false;
}
You can filter the data while querying the database.
Or - Filter rows from Cursor so they don't show up in ListView
Related
Here is the code, by this I can retrieve all the columns data from the database. But the problem is that now I want to retrieve only one column, that is my requirement.link1st link 2nd link3rd
word_list = new ArrayList<>();
SQLiteDatabase sd = mydb.getWritableDatabase();
Cursor cursor = sd.query("stickerstable",null, null, null, null, null, null);
if (cursor.moveToFirst()){
do{
word_list.add(new data_items(
cursor.getInt(cursor.getColumnIndex(ID)),
cursor.getString(cursor.getColumnIndex(STICKER_AUTHOR)),
cursor.getString(cursor.getColumnIndex(STICKER_NAME)
)));
}while (cursor.moveToNext());
cursor.close();
sd.close();
}
You can use rawQuery instead of query
Cursor cursor = sd.rawQuery("SELECT YOUR_COLUMN FROM stickerstable",null);
replace YOUR_COLUMN with the name of column you want to retrieve you can even use your Constants like this
Cursor cursor = sd.rawQuery("SELECT " + ID + " FROM stickerstable",null);
or a better way to use String.format
Cursor cursor = sd.rawQuery(String.format("SELECT %s FROM stickerstable", ID),null);
UPDATE
you can use query and specify the column in the second argument
Cursor cursor = sd.query("stickerstable",new String[]{ID}, null, null, null, null, null);
when you pass null means get all columns
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;
I have a listview in my application that displays records according to the primary key _ID field with the lowest _ID number first. How can I change that so it is the highest _ID number first in the listview? i.e reverse the order.
The db query currently generating the listview is below. Thanks!
public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SLOC, DatabaseHelper.FLOC, DatabaseHelper.DSNM, DatabaseHelper.SDATE, DatabaseHelper.STIME };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
use this query:
Cursor c = mDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
You can use rawQuery method to hit any custom query like this and add ORDER BY ASC or DESC as you wish.
public Cursor fetch() {
String queryString = "SELECT * FROM tablename ORDER BY _id DESC"
Cursor cursor = sqLiteDatabase.rawQuery(queryString);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
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();
I want to pull a row from a data-filled cursor and store it in another object for other use.
my code:
SQLiteDatabase db = dbOpener.getReadableDatabase();
Cursor dataSet = db.query(WPTemplateDB.PRODUCT_TABLE,
null, //all columns
null, //where clause
null, //where clause args
null, null, null);//groupBy, having, orderBy
while (dataSet.moveToNext()){
Product product = new Product(dataSet);
pArray.add(product);
}
my storing object:
public Product(Cursor cursor){
productData = cursor;
}
public String getData(String column){
Log.d(column, productData.getColumnIndex(column)+"");
return productData.getString(productData.getColumnIndex(column));
}
Now, I am facing an error of "index 10 requested with a size of 10". What can I do to this?
Don't should using cursor is contructors for Product objects. It will leak memory because cursor must close when not use.
You should read data from cursor then send data to contructor Product like:
String productName = cursor.getString(0);// 0 is column name
......
cursor.close();
Product product = new Product(name);
Indexes are zero-based. It means that is size is 10, max index will be 9. From the code you've posted, everything is fine, so the error in some other place of your code.
Actually, this answer is inspired from #cuasodayleo, I just translate it to be another code.
SQLiteDatabase db = dbOpener.getReadableDatabase();
Cursor dataSet = db.query(WPTemplateDB.PRODUCT_TABLE,
new String[]{WPTemplateDB.PRODUCT_ID},
null, //where clause
null, //where clause args
null, null, null);//groupBy, having, orderBy
while (dataSet.moveToNext()){
Product product = new Product(dataSet.getInt(0), db);
pArray.add(product);
}
dataSet.close();
The Product object:
public Product(int pid, SQLiteDatabase db){
productData = db.query(WPTemplateDB.PRODUCT_TABLE,
null, //all columns
WPTemplateDB.PRODUCT_ID+"=?", //where clause
new String[]{pid+""}, //where clause args
null, null, null);//groupBy, having, orderBy
}
public String getData(String column){
Log.d("count", productData.getCount()+"");
if (productData.getCount()>0){
Log.d(column, productData.getColumnIndex(column)+"");
productData.moveToFirst();
return productData.getString(productData.getColumnIndex(column));
} else {
return null;
}
}