2011-09-21 38 views
2

表字段:SQLiteDatabase如何在SQLiteDatabase查詢和SimpleCursorAdapter中連接兩個字符串?

_id,街道,house_nr

查詢:

mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_STREET_NAME, 
       KEY_HOUSE_NUMBER}, null, null, null, null, KEY_ROWID + " DESC"); 

SimpleCursorAdapter:

Cursor c = mDbHelper.fetchAllRows(); 
    startManagingCursor(c); 

    String[] from = new String[] { HistoryDbAdapter.KEY_STREET_NAME}; 
    int[] to = new int[] { R.id.text1 }; 

    SimpleCursorAdapter entries = 
     new SimpleCursorAdapter(this, R.layout.history_row, c, from, to); 
    setListAdapter(entries); 

如何添加一個組合字符串從兩個數據庫字段轉換爲R.id.text1以顯示完整地址。

例如:

street = "Android street" 
house_nr = "911" 

則:

R.id.text1 = "Android street 911" 

感謝

回答

3

有兩種方式:

  • Concat查詢中的兩個列名:KEY_STREET_NAME +「|| 「+ KEY_HOUSE_NUMBER我會用一個rawQuery然後

  • 使用自定義適配器

+0

嗯,也許查詢..或者也許有人有自定義適配器,正如我需要:d – Vytautas

+0

這是你的descision對於一個簡單的列表,就像你出我會改變。查詢。但是,如果這回答你的問題,不要忘記接受這個答案。 –

0

它的工作原理:。

public class HistoryCursorAdapter extends SimpleCursorAdapter { 
    private final LayoutInflater mInflater; 

    public HistoryCursorAdapter(Context context, int layout, Cursor c, 
      String[] from, int[] to) { 
     super(context, layout, c, from, to); 

     mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 
    @Override 
    public View getView (int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     if (convertView == null) { 
      convertView = mInflater.inflate(R.layout.history_row, null); 

      holder = new ViewHolder(); 
      holder.text = (TextView) convertView.findViewById(R.id.text1); 

      convertView.setTag(holder); 
     } else { 
      holder = (ViewHolder) convertView.getTag(); 
     } 
     Cursor c = getCursor(); 
     c.moveToPosition(position); 
     int street_index = c.getColumnIndex(HistoryDbAdapter.KEY_STREET_NAME); 
     int house_nr_index = c.getColumnIndex(HistoryDbAdapter.KEY_HOUSE_NUMBER); 
     holder.text.setText(String.format("%s %s", c.getString(street_index), c.getString(house_nr_index))); 
     return convertView; 

    } 

    static class ViewHolder { 
     TextView text; 
    } 
} 

那是我第一次也許可以所著更加簡單。 ?也許任何速度的建議

+0

一個自定義的CursorAdapter的一個非常乾淨的例子可以在這裏找到:http://blog.cluepusher.dk/2009/11/16/creating-a-custom-cursoradapter-for-android/ –