2013-04-21 76 views
0

我SQLite數據庫表是這樣的:如何選擇記錄一對一場的SQLite的Android隨機

_id || Column1 || Column2 || 
1 || test1 || a,b,c,d,e,f || 
2 || test2 || g,h,i,j,k,l || 
3 || test3 || m,n,o,p,q,r || 

如何選擇一個隨機列2,從這個表?

我想要的結果是這樣的:

_id || Column1 || Column2 || 
1 || test1 || d   || 
2 || test2 || k   || 
3 || test3 || r   || 

假定d,K,R是每個記錄的列2的隨機值。

感謝

更新: 我創建CustomAdapter並添加一些景觀是這樣的:

@Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
     Cursor c = getCursor(); 
     final LayoutInflater inflater = LayoutInflater.from(context); 
     View v = inflater.inflate(layout, parent, false); 
     int column2Name= c.getColumnIndex(DBAdapter.COLUMN2); 
     String col2Name= c.getString(column2Name); 
     String[] temp; 
     Random random = new Random(); 
      temp = col2Name.split(","); 
      String col2 = temp[random.nextInt(temp.length)]; 
     TextView col2_name = (TextView) v.findViewById(R.id.column2_label); 
     if (col2_name != null) { 
      col2_name .setText(col2); 
     } 
     return v; 
    } 

    @Override 
    public void bindView(View v, Context context, Cursor c) { 
     int column2Name= c.getColumnIndex(DBAdapter.COLUMN2); 
      String col2Name= c.getString(column2Name); 
      String[] temp; 
      Random random = new Random(); 
       temp = col2Name.split(","); 
       String col2 = temp[random.nextInt(temp.length)]; 
      TextView col2_name = (TextView) v.findViewById(R.id.column2_label); 
     if (col2_name != null) { 
      col2_name .setText(col2); 
     } 
    } 

現在,只需使用customAdapter您的活動,使COLUMN2可以顯示爲1個隨機值。

+0

嘗試'通過隨機()LIMIT 1從表順序列;'http://stackoverflow.com/questions/1253561/sqlite-order-by-rand – 2013-04-21 01:32:50

+0

不,我的意思是,不是所有的列顯示隨機,但只記錄Column2 – wdyz 2013-04-21 01:34:39

+0

y y或http://stackoverflow.com/questions/4114940/select-random-rows-in-sqlite – 2013-04-21 01:35:22

回答

2

一旦從數據庫獲得數據,在Java中執行操作將會容易得多。

Random RANDOM = new Random(System.currentTimeMillis()); 

int index = cursor.getColumnIndex("Column2"); 
String value = cursor.getString(index); 
String[] values = value.split(","); 
String randomValue = values[RANDOM.nextInt(values.length)];