Search code examples
androidarraylistandroid-sqlite

How do I change arraylist of ids into arraylist of other column values SQLite?


I have a backend-filtered Arraylist of Students Ids which I display in a listview. Instead of Ids I want to write the names which are stored in another table. Right now I filter the Ids like this:

public Cursor getAllSlots(String TimeId) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_SLOTS + " WHERE timeid = '" + TimeId +"'", null);
    return res;
}

Then I use this to display the Student IDs I got back from my database like so:

Cursor cursormo = myDb.getAllSlots(TimeId);  
while(cursormo.moveToNext()){
                    HashMap<String, String> resultMap = new HashMap<>();
                    resultMap.put("Name", cursormo.getString(1));
                    listItems.add(resultMap);
                    arrayListStudentsTime.add(cursormo.getString(1));
                }

And now I need to get the names of the Student IDs from another table. So I tried to transfer the Arraylist "arrayListStudentsTime" to my database and try this:

public Cursor getNamesbyIDs(ArrayList StudentIds) {
    Log.d("CREATION", "getNamebyID() called");
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id = '" + StudentIds +"'", null);
    return res;
}

But it doesn't work... Does anybody have an idea? Thanks in advance!!


Solution

  • change this:

    Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id = '" + StudentIds +"'", null);
    

    to:

    String commaSeperatedIds= String.join(",", StudentIds);
    
    Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id in (" + commaSeperatedIds+")", null);