0

Quero capturar latitude e longitude de dados que estão no Firebase e adicionar como marcadores no Google maps. Estou recebendo erro de null object reference na linha 136>> String latitude = dataSnapshotChild.child("latitude").getValue().toString();

Como pode ver no logcat estou conseguindo capturar a latitude e longitude e imprimindo com Log.v, mas dá o erro abaixo e o app fecha. Tenho só essa classe e o layout. O que está errado nesse código?

Minha estrutura no Firebase está assim:

Data
    uploads
          -KqQSusAUJs_MQs_giJr
                latitude: -16.160159
                longitude: -37.160730
          -KqQquseUJs_MQs_gits
                latitude: -14.692552
                longitude: -37.399593

Meu Código:

public class MainActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
    final static int PERMISSION_ALL = 1;
    final static String[] PERMISSIONS = {android.Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private GoogleMap mMap;
    MarkerOptions mo;
    Marker marker;
    LocationManager locationManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseApp.initializeApp(this);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mo = new MarkerOptions().position(new LatLng(0, 0)).title("Eu estou aqui!");
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionGranted()) {
            requestPermissions(PERMISSIONS, PERMISSION_ALL);
        } else requestLocation();
        if (!isLocationEnabled())
            showAlert(1);
    }



    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        marker = mMap.addMarker(mo);


        ref.child("uploads").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Iterator<DataSnapshot> dataSnapshotsChat =  dataSnapshot.getChildren().iterator();

                while (dataSnapshotsChat.hasNext()) {
                    DataSnapshot dataSnapshotChild = dataSnapshotsChat.next();
                     String latitude = dataSnapshotChild.child("latitude").getValue().toString();
                     String longitude = dataSnapshotChild.child("longitude").getValue().toString();
                     double latitude1 = Double.parseDouble(latitude);
                     double longitude1 = Double.parseDouble(longitude);
                     LatLng local = new LatLng(latitude1, longitude1);


            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });

    }


    private LatLngBounds maplocal = new LatLngBounds(
            new LatLng(-16.5191275, -49.7484793), new LatLng(-16.5191275, -49.7484793));

    @Override
    public void onLocationChanged(Location location) {
        LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
        marker.setPosition(myCoordinates);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(maplocal.getCenter(), 12));


    }

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

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
    private void requestLocation() {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        String provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(provider, 10000, 10, this);
    }
    private boolean isLocationEnabled() {
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }

    private boolean isPermissionGranted() {
        if (checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED || checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("mylog", "Permission is granted");
            return true;
        } else {
            Log.v("mylog", "Permission not granted");
            return false;
        }
    }
    private void showAlert(final int status) {
        String message, title, btnText;
        if (status == 1) {
            message = "Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                    "use this app";
            title = "Enable Location";
            btnText = "Location Settings";
        } else {
            message = "Please allow this app to access location!";
            title = "Permission access";
            btnText = "Grant";
        }
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setCancelable(false);
        dialog.setTitle(title)
                .setMessage(message)
                .setPositiveButton(btnText, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        if (status == 1) {
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        } else
                            requestPermissions(PERMISSIONS, PERMISSION_ALL);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        finish();
                    }
                });
        dialog.show();
    }


}

logcat:

08-06 20:32:59.201 31120-31120/com.chico.testemarker V/log: lat/lng: (-16.160159,-37.160730)
08-06 20:32:59.201 31120-31120/com.chico.testemarker V/log: lat/lng: (-14.692552,-37.399593)
08-06 20:32:59.201 31120-31120/com.chico.testemarker D/AndroidRuntime: Shutting down VM
08-06 20:32:59.201 31120-31120/com.chico.testemarker E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                              at com.chico.testemarker.MainActivity$1.onDataChange(MainActivity.java:136)
                                                                              at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
                                                                              at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                                                                              at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:158)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:7230)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
08-06 20:32:59.241 31120-31435/com.chico.testemarker I/DynamiteModule: Considering local module com.google.android.gms.tagmanager:9 and remote module com.google.android.gms.tagmanager:12
08-06 20:32:59.241 31120-31435/com.chico.testemarker I/DynamiteModule: Selected remote version of com.google.android.gms.tagmanager, version >= 12
08-06 20:32:59.251 31120-31509/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.251 31120-31509/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.251 31120-31512/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.251 31120-31509/com.chico.testemarker I/qtaguid: Tagging socket 35 with tag 3000110100000000{805310721,0} uid -1, pid: 31120, getuid(): 10228
08-06 20:32:59.251 31120-31512/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.251 31120-31511/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.251 31120-31511/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.251 31120-31511/com.chico.testemarker I/qtaguid: Tagging socket 97 with tag 3000110100000000{805310721,0} uid -1, pid: 31120, getuid(): 10228
08-06 20:32:59.251 31120-31512/com.chico.testemarker I/qtaguid: Tagging socket 83 with tag 3000110100000000{805310721,0} uid -1, pid: 31120, getuid(): 10228
08-06 20:32:59.261 31120-31510/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.261 31120-31510/com.chico.testemarker I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-06 20:32:59.261 31120-31510/com.chico.testemarker I/qtaguid: Tagging socket 98 with tag 3000110100000000{805310721,0} uid -1, pid: 31120, getuid(): 10228
08-06 20:32:59.421 31120-31435/com.chico.testemarker W/GoogleTagManager: No container asset found in /assets/containers. Checking top level /assets directory for container assets.
08-06 20:32:59.461 31120-31120/com.chico.testemarker E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.chico.testemarker, PID: 31120
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                           at com.chico.testemarker.MainActivity$1.onDataChange(MainActivity.java:136)
                                                                           at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
                                                                           at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                                                                           at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:158)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:7230)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
08-06 20:32:59.471 31120-31435/com.chico.testemarker W/GoogleTagManager: Tag Manager's event handler WILL NOT be installed (no container loaded)
08-06 20:32:59.471 31120-31435/com.chico.testemarker I/GoogleTagManager: Tag Manager initilization took 206ms
08-06 20:32:59.481 31120-31824/com.chico.testemarker I/FirebaseCrash: Sending crashes

1 Resposta 1

0

Consegui resolver retirando essa parte do código. Acho que estava dando conflito com a geolocalização.

private LatLngBounds maplocal = new LatLngBounds(
            new LatLng(-16.5191275, -49.7484793), new LatLng(-16.5191275, -49.7484793));

    @Override
    public void onLocationChanged(Location location) {
        LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
        marker.setPosition(myCoordinates);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(maplocal.getCenter(), 12));


    }

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

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
    private void requestLocation() {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        String provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(provider, 10000, 10, this);
    }
    private boolean isLocationEnabled() {
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }

    private boolean isPermissionGranted() {
        if (checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED || checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("mylog", "Permission is granted");
            return true;
        } else {
            Log.v("mylog", "Permission not granted");
            return false;
        }
    }
    private void showAlert(final int status) {
        String message, title, btnText;
        if (status == 1) {
            message = "Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                    "use this app";
            title = "Enable Location";
            btnText = "Location Settings";
        } else {
            message = "Please allow this app to access location!";
            title = "Permission access";
            btnText = "Grant";
        }
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setCancelable(false);
        dialog.setTitle(title)
                .setMessage(message)
                .setPositiveButton(btnText, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        if (status == 1) {
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        } else
                            requestPermissions(PERMISSIONS, PERMISSION_ALL);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        finish();
                    }
                });
        dialog.show();
    }

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .