0

我有这样的 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 并添加了一些这样的视图:

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

4

1 回答 1

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)];
于 2013-04-21T02:03:27.103 回答