从Firebase检索数据并向地图添加书签时出错

时间:2017-08-07 01:41:23

标签: android google-maps firebase

我想捕获Firebase中的数据的纬度和经度,并在Google地图中添加为书签。但是它在第136行给出错误>>

String latitude = dataSnapshotChild.child("latitude").GetValue().ToString();

查看logcat,我能够捕获纬度和经度并使用Log.v进行打印,并在应用程序崩溃后进行打印。我只有这个类和布局。我的代码出了什么问题?

我的Firebase结构如下所示:

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

我的代码:

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("I am here!");
        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

2 个答案:

答案 0 :(得分:0)

尝试使用简单的东西,比如for循环而不是迭代器,我认为这就是导致你在null对象上调用toString()的原因。

答案 1 :(得分:0)

已解决,我认为它与&#34; public void onLocationChanged&#34;相冲突。我刚刚删除了那部分代码。有效!!!

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