0

I am trying to build an application where I use JSON to get the current latitude and longitude and also the address from it, but as soon as I click on the button I get an error in my log:

E/Volley: [5807] BasicNetwork.performRequest: Unexpected response code 400 for https://maps.googleapis.com/maps/api/geocode/json?latlng=0.00.0

The code is given below :

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)

Also I am not able to figure out as to why am I getting the values of latitude and longitude as 0.0.

Can anyone help ? Thank you :)

Pritom Mazumdar
  • 325
  • 5
  • 20

2 Answers2

0

There seems to be 3 problems there :

First :

The format of the JsonObjectRequest() seems to be completely wrong. The correct format is :

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

Refer this and this

Second : You are getting unexpected response from geocode API

To use google's geocode APIs, you will have to first get yourself the API key. The format should be something like : (refer to this document)

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

So you can see there, it needs the API key. You can read here to get the key. Also NOTE that there is a comma (,) between the latitude value and longitude value. Your code is missing that.

Third : You are getting lat and lng as 0.0

That is because the location data takes time to be fetched. The OS do not calls onLocationChange() until it has location data with certain precision. So, when you click on the button, you do not have the location updated till then. What you should do is, when user clicks the button, show him a progress bar with message updating location and dismiss it only when onLocationChange() is called. Use lat and lng only when 'onLocationChange()' is called at least once.

zeekhuge
  • 1,594
  • 1
  • 13
  • 23
  • I have been following https://stackoverflow.com/questions/20238197/get-current-location-using-json/20238474#20238474 while making the app, and as you said about the api key , the accepted answer in the post did not have it. – Pritom Mazumdar Jul 29 '17 at 19:45
  • Choice is upto you, if you wish to go according to a 3 year old ans. where the user might have thought it to be 'implicit', or to believe these [google docs](https://developers.google.com/maps/documentation/geocoding/intro), the owner of those APIs – zeekhuge Jul 29 '17 at 19:48
  • Okay, so as you said that I missed a coma , I fixed that and now the log shows something like this : `W/System.err: org.json.JSONException: Index 0 out of range [0..0)` – Pritom Mazumdar Jul 29 '17 at 19:50
  • I have updated the code and also displayed the `logcat` – Pritom Mazumdar Jul 29 '17 at 19:56
  • Updated the answer – zeekhuge Jul 29 '17 at 19:58
  • The log shows `index 0 out of range` , does it mean that I have to change the indexing part , I mean do I have to change this line : `String address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");` – Pritom Mazumdar Jul 29 '17 at 20:11
  • You should manually use that url in the browser and check the output. I think the `resultst` tag must be empty since you do not have the API key. – zeekhuge Jul 29 '17 at 20:17
  • http://maps.googleapis.com/maps/api/geocode/json?latlng=24.7593,92.7839&sensor=true , this is the url with my current latitude and longitude and it shows correct output – Pritom Mazumdar Jul 29 '17 at 20:19
0

I just had to change the format of JsonObjectRequest(). The correct format is given below as suggested by @ZeekHuge

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

The correct code is given below :

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);
}
}

Although by using this method it takes a lot of time to display the location.

Pritom Mazumdar
  • 325
  • 5
  • 20