如何随机选择一个字段SQLite Android上的记录之一

时间:2013-04-21 01:27:51

标签: android sqlite android-sqlite

我有这样的SQLite数据库表:

_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 ||

如何从此表中选择Column2的一个随机数?

我想要这样的结果:

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

假设d,k,r是每个记录的Column2的随机值。

由于

更新: 我创建了CustomAdapter并添加了一些这样的View:

  @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个随机值。

1 个答案:

答案 0 :(得分: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)];