在Sqlite Android中列出所有行的最佳方法是什么?

时间:2011-11-29 23:25:58

标签: android sqlite listview android-arrayadapter

我目前正在使用以下代码将某些列中的所有项目传递给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);
    }

有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

在我的应用程序中我使用这样的东西:

    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;
}

然后,您可以将arraylist放入适配器;) 像这样:

SimpleAdapter adapter = new MySimpleAdapter(this, selectLastSearch(), R.layout.custom_row_view, new String[] { "Icon", "Icon" }, new int[] { R.id.textView1123, R.id.imageView12 });

这是我的简单适配器:

    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;
    }
}

答案 1 :(得分:0)

是的,有一种更简单的方法。而不是手动写出sql选择让Android在数据库助手类中使用游标。这将选择表中没有选择参数的所有内容。

public Cursor getAllItems() {
    return this.sqliteDBInstance.query(EMPLOYEE_TABLE, null, null, null, null, null, null);
}

然后在您的活动中,您只显示名字,姓氏和标题,即使在getAllItems Cursor方法中选择了_id。我假设您不想在列表视图中显示它。

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