JSONオブジェクトと距離行列APIを使用して、2つの場所間の距離を見つけるために約30のhttpリクエストを行うasynctaskを実装しようとしています。私が書いたコードは、メインUIスレッドから呼び出されたときに機能しますが、非同期タスクから実行して配列までの距離を保存しようとすると、配列がnull値でいっぱいになってしまいます。何かアドバイス?(注:このコードは、最初は私の職場の誰かによって書かれました。コピーして貼り付け、アプリで動作するように数行変更しただけです。そのため、気付かない不要なビットがいくつかある可能性があります。感じてください。それらを自由に指摘してください)
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();
}
}