我一直在尝试实现 asynctask 以发出大约 30 个 http 请求,以使用 JSON 对象和距离矩阵 api 查找两个位置之间的距离。我编写的代码在从主 UI 线程调用时有效,但是当我尝试从异步任务运行它并将距离保存到一个数组时,我最终得到一个充满空值的数组。有什么建议吗?(注意:这段代码最初是由我工作中的其他人编写的,我只是复制粘贴它并更改了几行以使用我的应用程序。因此,可能有一些我不知道的不必要的位。感觉免费指出他们)
class DistanceFinder extends AsyncTask<String[], Void, String[]>
{
@Override
protected String[] doInBackground(String[]... locations)
{
String baseURL="https://maps.googleapis.com/maps/api/distancematrix/json?origins=";
String[] distances = new String[locations[1].length];
for(int i = 1;i<locations.length;i++)
{
String url = baseURL + locations[0][0].replace(" ","+") + "&destinations=" + locations[1][i].replace(' ', '+') + "&sensor=true&units=imperial";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = "";
boolean internet;
try
{
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
internet=true;
}
else
{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
internet=false;
Toast.makeText(getApplicationContext(), "Please connect to internet", Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
internet=false;
Toast.makeText(getApplicationContext(),"Please connect to internet", Toast.LENGTH_LONG).show();
}
if(internet){
try
{
JSONObject jsonObj = new JSONObject(responseString);
JSONArray rows = jsonObj.getJSONArray("rows");
JSONObject inRows=rows.getJSONObject(0);
JSONArray elements = inRows.getJSONArray("elements");
JSONObject inElements=elements.getJSONObject(0);
JSONObject distance= inElements.getJSONObject("distance");
distances[i] = distance.getString("text");
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return distances;
}
@Override
protected void onPostExecute(String[] result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
distancesList = result;
}
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
}