0

我正在尝试通过传递 lat 和 lon 以及 userID 来使用 sampleURL 调用 REST Web 服务。但我总是null输入字符串数据。有什么建议为什么会发生?我正在使用安卓系统。但是当我尝试在浏览器中打开该 url 时,它会被打开并且我可以看到响应。我猜我的代码有问题。

private class GPSLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            GeoPoint point = new GeoPoint(
                    (int) (location.getLatitude() * 1E6), 
                    (int) (location.getLongitude() * 1E6));

            String data = findUsersInCurrentRadius(1,location.getLatitude(),location.getLongitude());
            System.out.println("Got Data" +data);
            textView.setText(data);

}

private String findUsersInCurrentRadius(int userid, double lat, double lon) {

        String sampleURL = SERVICE_URL + "/"+REMOTE_METHOD_NAME+"/"+userid+"/"+lat+"/"+lon;
        System.out.println(sampleURL);

        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(sampleURL);
        String text = null;
        try {
            HttpResponse response = httpClient.execute(httpGet, localContext);
            System.out.println("Some Response" +response);
            HttpEntity entity = response.getEntity();
            text = getASCIIContentFromEntity(entity);
        } catch (Exception e1) {
            return e1.getLocalizedMessage();
        }
        return text;
    }

}

4

1 回答 1

1

您正在主 UI 线程上运行网络请求。使用 AsyncTask 执行网络请求。Android OS >= 3.0 不允许在主 UI 线程上运行网络请求。

你可以使用AsyncTask喜欢

    private class NetworkRequest extends AsyncTask<String, Void, String> {
    int userid;
    double lat, lon;
    String reponse;

    public NetworkRequest(int userID, double lat, double lon) {
        this.userid = userID;
        this.lon = lon;
        this.lat = lot;
    }

    @Override
    protected String doInBackground(String... params) {
        reponse = findUsersInCurrentRadius(userid, lat, lon);
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        if (null != reponse) {
            System.out.println("Got Data" + reponse);
            textView.setText(reponse);
        }
        else{
            //Handle the Error
        }
    }

}

然后在你的onLocationChanged电话中Async Task

new NetworkRequest(userid,lat,lon).execute();
于 2012-08-13T03:12:51.633 回答