2013-04-21 128 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)];