在循环数组之前等待AsyncTask完成
问题描述:
我有一个循环将一个候选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
new MyAsyncTask().execute(candidateId);
的可能的复制[你怎么能传递多个原始参数的AsyncTask?( http://stackoverflow.com/questions/12069669/how-can-you-pass-multiple-primitive-parameters-to-asynctask) –