Reputation: 17129
I'm currently using the following code to pass all items in some columns to Arrayadapter
.
private void TestListAll(){
//Displays the whole list.
cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?",
new String[]{"%" + "" + "%"});
adapter = new SimpleCursorAdapter(
this,
R.layout.emp_list_item,
cursor,
new String[] {"firstName", "lastName", "title"},
new int[] {R.id.firstName, R.id.lastName, R.id.title});
setListAdapter(adapter);
}
Is there a better method to accomplish this?
Upvotes: 2
Views: 5610
Reputation: 353
Yeah there is an easier way. Instead of writing out that sql select by hand let Android do it with a cursor in your database helper class. This selects everything in your table with no selection arguments.
public Cursor getAllItems() {
return this.sqliteDBInstance.query(EMPLOYEE_TABLE, null, null, null, null, null, null);
}
And then in your activity you only show firstname, lastname, and title even though _id was selected in the getAllItems Cursor method. I assume you do not want to show it in the listview.
Private Cursor cursor;
...
cursor = db.getAllItems();
startManagingCursor(cursor);
ListAdapter adapter = new SimpleCursorAdapter(MyActivity.this,
R.layout.emp_list_item, cursor, new String[] { "firstName", "lastName", "title" }, new int[] { R.id.firstName, R.id.lastName, R.id.title });
setAdapter(adapter);
Upvotes: 0
Reputation: 3084
in my app i use somethink like this:
public ArrayList<HashMap<String, ?>> selectLastPlayed() {
ArrayList<HashMap<String, ?>> list = new ArrayList<HashMap<String, ?>>();
Cursor cursor = this.db.query("employee Order BY ID DESC",
new String[] { "*" }, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, Object> temp = new HashMap<String, Object>();
temp.put("Icon", cursor.getString(1));
temp.put("Title", cursor.getString(2));
list.add(temp);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
and then, you can put arraylist into adapter ;) like this:
SimpleAdapter adapter = new MySimpleAdapter(this, selectLastSearch(), R.layout.custom_row_view, new String[] { "Icon", "Icon" }, new int[] { R.id.textView1123, R.id.imageView12 });
this is my simple adapter:
public class MySimpleAdapter extends SimpleAdapter {
Context localcontext = null;
public MySimpleAdapter(Context context,List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
localcontext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
return view;
}
}
Upvotes: 1