2017-04-22 74 views
0

我已經設置了一個應用程序,它目前可以在數據庫中查找一個輸入id,然後給出一個結果。例如。用戶輸入ID = 1,數據庫包含一個ID爲1的記錄,然後返回名稱或編號等...使用數組列表查詢數據庫並獲取結果數組列表

現在我想通過查詢我的數據庫,使用一個包含一系列id例如3,456,731等...我希望我的數據庫搜索。我也將多個值分組到特定的ID,例如數據庫可能會搜索3的ID它會找到5個結果我希望它將每個結果的電話號碼返回到另一個ArrayList,我可以打印到日誌。

我希望我已經解釋過了,但如果您需要更多信息,請提問。

下面的代碼演示了用於獲取單個結果的查詢的修改版本,但我無法看到我在做錯了什麼以獲得多個結果。

活動....

// New array list which is going to be used to store values from the database 
ArrayList<String> contactsList; 

// This arrayList has been received from another activity and contains my id's 
ArrayList<String> contacts = intent.getStringArrayListExtra("groupCode"); 

// The database which i'm using 
ContactDBHandler contactDBHandler = new ContactDBHandler(getApplicationContext(), null, null, 1); 

//getAllValues is used to pass my arraylist id's to the database. 
contactsList = contactDBHandler.GetAllValues(contacts); 


// Simple log statement to loop and display results 
for (int i = 0; i < contactsList.size(); i++){ 

     Log.i("Numbers", contactsList.get(i)); 

    } 

ContactDBHandler

查詢

// I'm telling it to get the contact number from the contact_list 
// when the groupcode matches the code recieved. 


public ArrayList<String> GetAllValues(ArrayList groupCode) 
{ 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = null; 
    String alarmName = ""; 
    ArrayList<String> list = new ArrayList<>(); 
    cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code=?", new String[]{groupCode+ ""}); 
    if (cursor.moveToFirst()) 
    { 
     do 
     { 
      list.add(cursor.getString(0)); 
     } 
     while (cursor.moveToNext()); 
    } 
    if (cursor != null && !cursor.isClosed()) 
    { 
     cursor.close(); 
    } 

    return list; 
} 

感謝 你能看到我在哪裏呢?

+0

您是否獲得一個異常或不輸出預期的結果不匹配? –

+0

目前我的日誌只是空的,也只是測試我的聯繫人數組列表,我可以確認它有ID等待使用。 – user3403733

回答

0

試試這個:

cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (" + TextUtils.join(",", Collections.nCopies(groupCode.size(), "?")) + ")", groupCode.toArray(new String[groupCode.size()])); 

您當前的代碼無法通過在SQL格式列表:=做只支持單個值,列表必須使用IN


您的代碼會導致這樣的查詢:

SELECT contact_number FROM contact_list WHERE grp_code=["some_id","other_id"] 

但你需要(和我的代碼生成)是什麼:

SELECT contact_number FROM contact_list WHERE grp_code IN ('some_id','other_id') 

參考文獻:

+0

嗨F43nd1r完美的答案,你也可以快速帶我通過你添加的小部分 – user3403733

+0

對不起,我不明白。你指的是哪一部分? – F43nd1r

+0

注意:已編輯以防止sql注入 – F43nd1r

0

您無法將ArrayList傳遞給SQLQuery。要檢查同一字段中的多個值,您必須使用'in'關鍵字。

例:

SELECT * FROM `table1` where column in ('element1', 'element2', 'element3') 

在你的情況,

String str = ""; 
for(String s: groupCode){ 
    str = str+","+"\'"+s+"\'"; 
} 
//to remove the extra ' in the begining 
str = str.substring(1); 
return str; 

cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (?)", new String[]{str}); 
相關問題