1
我有一個循環將一個候選ID分配給一個變量,該變量用於我的後臺任務以從數據庫中檢索數據。但是,因爲它是一個後臺任務,通過任務得到運行的時間,它只能使用最後一個ID:在循環數組之前等待AsyncTask完成
for (int i=0; i < id_array.length; i++) {
System.out.println("array");
System.out.println(id_array[i]);
candidate_id = id_array[i];
new BackgroundTask().execute();
}
它是循環正確(可以從我的輸出看),但它是相同的ID每次當我在後臺任務中調用candidate_id
時。我使用它作爲一個URL JSON請求的一部分:
class BackgroundTask extends AsyncTask<Void,Void,String> {
String json="http://[myip]/dan/db/getcandidatedetails.php?candidate_id=";
@Override
protected String doInBackground(Void... voids) {
System.out.println("Candidate ID******" + candidate_id);
String json_url= json + candidate_id;
System.out.println("url" + json_url);
...
它返回的候選人ID總是在循環中的最後一個。
有關如何解決此問題的任何建議/更有效的方法?在執行時AsyncTask
public static class MyAsyncTask extends AsyncTask<Integer, Void, String> {
@Override
protected String doInBackground(final Integer... integers) {
final int candidateId = integers[0];
// do some work here with `candidateId`
return "some_string";
}
}
然後:
的可能的複製[你怎麼能傳遞多個原始參數的AsyncTask?( http://stackoverflow.com/questions/12069669/how-can-you-pass-multiple-primitive-parameters-to-asynctask) –