2011-03-28 67 views
1

我想從我的SQLite數據庫填充的ListView ......我這是怎麼從數據庫中獲取我的數據:製作的ListView

Cursor c = database.rawQuery("SELECT * FROM " + TableName, null); 
    int Column1 = c.getColumnIndex("uri"); 
    int Column2 = c.getColumnIndex("file"); 
    int Column3 = c.getColumnIndex("id"); 
    c.moveToFirst(); 
    if (c != null) { 
     do { 
      String uri = c.getString(Column1); 
      String file = c.getString(Column2); 
      int id = c.getInt(Column3); 
     } while (c.moveToNext()); 
    } 

我通常會添加一個數組的ListView這樣的:

ListView my_listview2 = (ListView) findViewById(R.id.listView1); 
    String my_array[] = {"Android", "iPhone"}; 
    my_listview2.setAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.my_custom_row, my_array)); 

我怎樣才能讓一個數組從我的SQL查詢來setadapter?

回答

5

這樣做的最好方法是使用CursorAdapter或SimpleCursorAdapter。這會給你提供最好的性能,一旦你發現它,你會發現這是使用SQLite數據庫時最簡單的方法。

http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html

下面是一個簡單CustomCursorAdapter,我經常使用。只需將CustomCursorAdapter類添加爲內部類即可。

protected class CustomCursorAdapter extends SimpleCursorAdapter { 
     private int layout; 
     private LayoutInflater inflater; 
     private Context context; 

     public CustomCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) { 
      super(context, layout, c, from, to); 
      this.layout = layout; 
      this.context = context; 
      inflater = LayoutInflater.from(context); 

     } 


     @Override 
     public View newView(Context context, Cursor cursor, ViewGroup parent) { 
      Log.i("NewView", newViewCount.toString()); 

      View v = inflater.inflate(R.layout.list_cell, parent, false); 

      return v; 
     } 

     @Override 
     public void bindView(View v, Context context, Cursor c) { 
        //1 is the column where you're getting your data from 
      String name = c.getString(1); 
      /** 
      * Next set the name of the entry. 
      */ 
      TextView name_text = (TextView) v.findViewById(R.id.textView); 
      if (name_text != null) { 
       name_text.setText(name); 
      } 
     } 

像這樣創建CustomCursorAdapter的實例... 你需要創建你的光標,就像你已經做。

protected String[] from; 
protected int[] to; 

    //From is the column name in your cursor where you're getting the data 
    //to is the id of the view it will map to 
    from = new String[]{"name"}; 
    to = new int[]{R.id.textView}; 

CustomCursorAdapter adapter = new CustomCursorAdapter(this, R.layout.list, cursor, from, to); 
listView.setAdapter(adapter); 
+0

這是一個很好的例子。感謝你的分享。 – wojciii 2013-03-19 21:28:06