在 Android 中调用 REST Web 服务并在字符串数据中获取空值



我试图通过传递lat and lon和userID来调用REST Web Service。但我总是在字符串数据中得到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;
    }

}

您正在主 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();

最新更新