有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何用一组字符串数组从数据库中获取数据

我有一组字符串,它是:

"1,2,5,6,9,17,24"

它们中的每一个都是“User”表的用户ID

如果userID是在of字符串中指定的,如何从表中获取多行数据

我有一个建议,就是用substring拆分字符串,并for循环dbhelper中的每个id,但我不知道该怎么做

以下是我的Activity的代码:

private void loadChatData() {
    String GroupName = Groupname;
    String participantID = dbHelper.getParticipantID(GroupName);
    participants = dbHelper.getParticipantList(participantID);
    madapter = new FriendListByGridAdapter(GroupinformationActivity.this, participants);
    groupdetailsdelist.setAdapter(madapter);
    madapter.notifyDataSetChanged();
}

参与者ID的输出为“1,2,5,6,9,17,24”

以下是DBHelpers中方法的代码:

  public List<Friend> getParticipantList(String participantID) {
      openForWrite();
      List<Friend> list = new ArrayList<Friend>();
      String selectQuery ="SELECT "
            + KEY_FRIEND_NAME + ","
            + KEY_PICTURE
            + " FROM "
            + TABLE_FRIEND
            + " WHERE "
            + KEY_FRIEND_ID + " = "
            + "'"+ participantID + "'";

    Cursor cursor = db.rawQuery(selectQuery, new String[]{});

    if (cursor.moveToFirst()) {

        do {
            Friend temp = new Friend();
            temp.setFriendpicture(cursor.getString(cursor.getColumnIndex(KEY_PICTURE)));
            temp.setFriend_name(cursor.getString(cursor.getColumnIndex(KEY_FRIEND_NAME)));

            list.add(temp);
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    Log.d("friend list","" + list.size());
    return list;
}

我只想让所有的friendNamepicturepath显示在与字符串中的userID相对应的listview

下面是我的“朋友”表的一个示例: Table_Friend


共 (2) 个答案

  1. # 1 楼答案

    这可能会帮助您:

    String participentIDArray[] = participentID.split(",");
    List<Friend> list = new ArrayList<Friend>();
    for(int i = 0; i < participentIDArray.length; i++) {
        list.addAll(getDataFromDatabase(participentIDArray[i]));
    }
    madapter = new FriendListByGridAdapter(GroupinformationActivity.this, list);
    groupdetailsdelist.setAdapter(madapter);
    madapter.notifyDataSetChanged();
    

    基于participentID从数据库获取数据的方法:

    public ArrayList<Friend> getDataFromDatabase() {
        List<Friend> list = new ArrayList<Friend>();
        // Add your code to get data from database
        return list;
    }
    
  2. # 2 楼答案

    如果我理解正确,您希望在一个查询中获取所有ID。因此,您可以创建一个简单的sql,例如:

    "SELECT * FROM TABLE_FRIEND WHERE KEY_FRIEND_ID in (participantID)";
    

    然后使用:

    db.rawQuery(sql,null);