1

我一直在尝试实现 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();
    }

}
4

1 回答 1

0

你的问题在于你的 for 循环

for(int i = 1;i<locations.length;i++)

首先,您应该从 0 开始,除非您的第一个单元格没有存储String您希望检查到的距离。

其次,你的 for 循环应该是

for(int i = 0;i<locations[0].length;i++)

现在你正在检查单元格[1][0],就是这样,因为循环结束了。

我用手动输入的位置对其进行了测试,它可以工作。

另外,为了让您更容易调试,您应该真正习惯使用Log.d(). 它确实有助于找出错误。我在您的代码中使用了它,发现循环只执行一次。

祝你好运

Ps,正如其中一条评论中提到的,删除onPreExecute(). 你不使用它。

于 2012-08-31T23:17:09.333 回答