Search code examples
androidgoogle-mapsandroid-volleylocationlistener

Locationlistener is null


The error comes because of the location listener is null.I put the location listener in the JsonObjectRequest of volley library. my code is

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, mLocationListener);

    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        // Add a marker in Sydney and move the camera
        UiSettings uiSettings=mMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(true);
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        requestQueue= Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, loginUrl, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONArray ja = response.getJSONArray("hi");
                    retid= new String[ja.length()];
                    retph= new String[ja.length()];
                    retname=new String[ja.length()];
                    retlat= new Double[ja.length()];
                    retlong= new Double[ja.length()];
                    for(int i=0;i<ja.length();i++){
                        JSONObject jsonObject=ja.getJSONObject(i);
                        if(!(jsonObject.getString("retailer_loc_lat").equals("0")&&jsonObject.getString("retailer_loc_long").equals("0"))) {
                            retid[i] = jsonObject.getString("retailer_id") + "";
                            retname[i] = jsonObject.getString("retailer_first_name") + " " + jsonObject.getString("retailer_last_name");
                            retlat[i] = Double.parseDouble(jsonObject.getString("retailer_loc_lat"));
                            retlong[i] = Double.parseDouble(jsonObject.getString("retailer_loc_long"));
                            retph[i] = "Phone:" + jsonObject.getString("retailer_ph_no");

                        }
                    }

                   mLocationListener = new LocationListener() {
                                @Override
                                public void onLocationChanged(final Location location) {
                                    for(int j=0;j<retid.length;j++){
                                        if(almostEqual(retlat[j],location.getLatitude(),.5)&&almostEqual(retlong[j],location.getLatitude(),.5)){
                                            mMap.addMarker(new MarkerOptions().position(new LatLng(retlat[j], retlong[j])).title(retname[j]).snippet(retph[j]).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin_96)));
                                        }
                                    }

                                }

                                @Override
                                public void onStatusChanged(String provider, int status, Bundle extras) {

                                }

                                @Override
                                public void onProviderEnabled(String provider) {

                                }

                                @Override
                                public void onProviderDisabled(String provider) {

                                }
                            };


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });requestQueue.add(jsonObjectRequest);

    }

my log cat

Caused by: java.lang.IllegalArgumentException: invalid listener: null
                                                                     at android.location.LocationManager.checkListener(LocationManager.java:1606)
                                                                     at android.location.LocationManager.requestLocationUpdates(LocationManager.java:426)

The main reason is that the location manager cant get the location listener in the JsonObjectRequest. Please help.


Solution

  • mapFragment.getMapAsync(this); is an aysnchronous non-blocking call. Hence
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, mLocationListener);
    gets executed before you get onMapReady() callback. Now since mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, mLocationListener); gets executed before onMapReady() , mLocationListener is null since you haven't initialized it before. And that's why you get Exception.