BasicNetwork.performRequest:android中的意外响应代码400

时间:2017-07-29 19:19:14

标签: android json android-volley android-gps

我正在尝试构建一个应用程序,我使用JSON从中获取当前latitudelongitude以及address,但是只要我点击在button我的日志中收到错误:

  

E / Volley:[5807] BasicNetwork.performRequest:https://maps.googleapis.com/maps/api/geocode/json?latlng=0.00.0的意外响应代码400

代码如下:

Gps3Activity.java

    public class Gps3Activity extends AppCompatActivity {
    private Button display;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private RequestQueue requestQueue;
    private double lat;
    private double lng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps3);

        display = (Button) findViewById(R.id.displayL);
        requestQueue = Volley.newRequestQueue(this);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new myLocationlistener();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);

        display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Log.e("Latitude", String.valueOf(lat));
                Log.e("Longitude", String.valueOf(lng));

                JsonObjectRequest request = new JsonObjectRequest("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true", new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
                            //textViewCity.setText(address);
                            Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(request);
            }
        });
    }

    private class myLocationlistener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                lat = location.getLatitude();
                lng = location.getLongitude();
            }
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }
}

logcat的

07-30 01:18:33.287 9750-9750/com.example.shaloin.gps2 W/System.err: org.json.JSONException: Index 0 out of range [0..0)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at org.json.JSONArray.get(JSONArray.java:293)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at org.json.JSONArray.getJSONObject(JSONArray.java:521)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at com.example.shaloin.gps2.Gps3Activity$1$1.onResponse(Gps3Activity.java:63)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at com.example.shaloin.gps2.Gps3Activity$1$1.onResponse(Gps3Activity.java:58)

此外,我无法弄清楚为什么我将latitudelongitude的值设为0.0

有人可以帮忙吗?谢谢:))

2 个答案:

答案 0 :(得分:0)

那里似乎有3个问题:

首先:

JsonObjectRequest()的格式似乎完全错误。正确的格式是:

JsonObjectRequest(int method,
                  String url,
                  JSONObject jsonRequest,
                  Response.Listener<JSONObject> listener,
                  Response.ErrorListener errorListener)

参考thisthis

第二:您将从地理编码API

获得意外回复

要使用Google的地理编码API,您必须首先获得API密钥。 格式应类似于:(参考this文档)

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&location_type=ROOFTOP&result_type=street_address&key=YOUR_API_KEY

所以你可以看到它,它需要API密钥。您可以阅读here以获取密钥。另外注意纬度值和经度值之间有一个逗号(,)。你的代码遗失了。

第三:您的latlng为0.0

这是因为位置数据需要时间来获取。操作系统在具有一定精度的位置数据之前不会调用onLocationChange()。因此,当您单击按钮时,您之前没有更新位置。您应该做的是,当用户点击该按钮时,向他显示一条带有消息updating location的进度条,并仅在调用onLocationChange()时将其关闭。仅当'onLocationChange()'被调用至少一次时才使用latlng

答案 1 :(得分:0)

我只需要更改JsonObjectRequest()的格式。正如@ZeekHuge

所建议的那样,下面给出了正确的格式
JsonObjectRequest(int method,
              String url,
              JSONObject jsonRequest,
              Response.Listener<JSONObject> listener,
              Response.ErrorListener errorListener)

下面给出了正确的代码:

public class Gps3Activity extends AppCompatActivity {

private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
private Button display;
private TextView displayLocation;
private LocationManager locationManager;
private LocationListener locationListener;
private RequestQueue requestQueue;
private double lat;
private double lng;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gps3);

    display = (Button) findViewById(R.id.displayL);
    displayLocation=(TextView)findViewById(R.id.location1);
    requestQueue = Volley.newRequestQueue(this);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationListener = new myLocationlistener();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);

    display.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            getLocation(lat,lng);

            Log.e("Latitude", String.valueOf(lat));
            Log.e("Longitude", String.valueOf(lng));
            Log.e("city",address);
            Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
            displayLocation.setText("City : "+address);
}
    });
}

private class myLocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
            //Toast.makeText(getApplicationContext(),"Latitude: "+lat+"\nLongitude: "+lng,Toast.LENGTH_LONG).show();
            getLocation(lat,lng);
        }
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}

public void getLocation(double latitude,double longitude){
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ latitude+","+longitude +"&sensor=true",
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    try {
                        address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
                        //textViewCity.setText(address);
                        //Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    requestQueue.add(request);
}
}

虽然使用此方法需要花费大量时间来显示location