Gaby Gaby - 18 days ago 9
Android Question

How can I see only the items from a database table which have a certain id?

In my database I have 2 tables. For a table I want to display only the items which has a certain id in the second column. I have an adapter for all the items from the table but I don't know how should it look like for viewing only the items I need. Any idea is welcome.

Here is my adapter :

private void populate(){
c=prod.fetchAll();
startManagingCursor(c);

adapter=new SimpleCursorAdapter(this,R.layout.listproduct,c,
new String[] {ProductDbAdapter.KEY_ITEM,ProductDbAdapter.KEY_QUANTITY,ProductDbAdapter.KEY_UNITS},
new int[] {R.id.prod1,R.id.prod2,R.id.prod3});

lv.setAdapter(adapter);

}


The code for ProductDbAdapter is :

public class ProductDbAdapter extends AbstractDbAdapter {

public static final String KEY_LISTID = "list_id";
public static final String KEY_ITEM = "item";
public static final String KEY_QUANTITY="quantity";
public static final String KEY_UNITS="units";

public static final String KEY_ROWID = "_id";

private static final String DATABASE_TABLE = "products";


public ProductDbAdapter(Context ctx) {
super(ctx);
}


public long create(Integer listid, String item,String quantity,String units) {
ContentValues args = new ContentValues();
args.put(KEY_LISTID,listid);
args.put(KEY_ITEM,item);
args.put(KEY_QUANTITY,quantity);
args.put(KEY_UNITS,units);

return mDb.insert(DATABASE_TABLE, null,args);
}


public boolean updateproduct(long rowId,Integer listid, String item,String quantity,String units) {
ContentValues values = new ContentValues();
values.put(KEY_LISTID, listid);
values.put(KEY_ITEM, item);
values.put(KEY_QUANTITY, quantity);
values.put(KEY_UNITS,units);
return mDb.update(DATABASE_TABLE, values, KEY_ROWID + "="+ rowId, null) > 0;
}

public boolean delete(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}


public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LISTID,KEY_ITEM,KEY_QUANTITY,
KEY_UNITS}, null, null, null, null, null);
}


public Cursor fetch(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_LISTID,KEY_ITEM,KEY_QUANTITY, KEY_UNITS}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;

}
}


What I am trying to do is to display only the items with a certain list_id..

Flo Flo
Answer

Why do you request a cursor which returns all item when you only want items with a certain id? Change your database query so you only get the items with the ids you define in the where-statement of your database query.

Let the database so the job of filtering the correct items for you, it's not the job of an adapter.

Comments