2011-09-21 41 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/ –