2011-11-29 67 views
2

我正在使用以下代碼將某些列中的所有項目傳遞給Arrayadapter在Sqlite Android中列出所有行的最佳方式是什麼?

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

有沒有更好的方法來實現這個目標?

回答

1
在我的應用程序

我somethink使用這樣的:

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

如何將ArrayList放入arrayadapter? –

+0

像這樣:SimpleAdapter adapter = new MySimpleAdapter(this,selectLastSearch(),R.layout.custom_row_view,new String [] {「Icon」,「Icon」},new int [] {R.id.textView1123,R.id .imageView12}); lv.setAdapter(adapter); –

+0

謝謝。我會試試看。 –

0

是的,有一個更簡單的方法。不要用手寫出sql,而要讓Android在數據庫輔助類中使用遊標。這會選擇表中沒有選擇參數的所有內容。

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

然後在你的活動,你只顯示名字,姓氏和標題即使_id是在getAllItems光標方法來選擇。我假設你不想在列表視圖中顯示它。

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); 
相關問題