2011-03-28 43 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