将数据写入Firebase,但应用程序停止

时间:2019-02-03 19:09:04

标签: android firebase firebase-realtime-database

我正在尝试将数据写入Firebase,但是在调用savetoFirebase函数时,应用程序停止了。 我认为savetoFirebase函数存在某些错误,或者Firebase没有正确集成。 这是功能代码。

private void saveToFirebase() {
        Location location = new Location("dummyprovider");
        LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
        Location mCurrentLocation = location;
        Map mLocations = new HashMap();
        Map  mCoordinate = new HashMap();
        mCoordinate.put("Latitude", mCurrentLocation.getLatitude());
        mCoordinate.put("Longitude", mCurrentLocation.getLongitude());
        mLocations.put("location", mCoordinate);
        String url = "MY-FIREBASE-APP";
        DatabaseReference myFirebaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl(url);
        myFirebaseRef.push().setValue(mLocations);

    }

当加速度计的y轴更改时,我正在调用此函数,当此值更改时,还会发出蜂鸣声。 蜂鸣声仍在播放,但是该应用程序停止运行并显示弹出窗口表明该应用程序已停止。

以下是该应用的完整代码:

package com.example.hamzah.potholetrackingandmapping;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.IgnoreExtraProperties;
import com.google.firebase.database.ValueEventListener;

import java.util.HashMap;
import java.util.Map;


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

    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private Sensor mAcc;
    private float mLastX, mLastY, mLastZ;
    private boolean mInitialized;
    private MediaPlayer player;


    @Override
    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);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        // Get the default sensor of specified type
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this,mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        player = MediaPlayer.create(this, R.raw.beep);
        mapFragment.getMapAsync(this);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
        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);
    }


    @Override
    public void onLocationChanged(Location location) {
        LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
        marker.setPosition(myCoordinates);
        int zoom = 15;
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoom));
    }

    @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_COARSE);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        String provider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_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;
        }
        locationManager.requestLocationUpdates(provider, 100, 10, this);
    }

    private boolean isLocationEnabled() {
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }
    private boolean isPermissionGranted(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED || checkSelfPermission(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;
            }
        }
        return false;
    }
    private void showAlert(final int status) {
        String message, title, btnText;
        if (status == 1) {
            message = "Your Location Setting 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() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @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();
    }


    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this,mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }


    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (!mInitialized) {
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            mInitialized = true;
        } else {

            float deltaY = y - mLastY;
            float deltaZ = z - mLastZ;

            mLastX = x;
            mLastY = y;
            mLastZ = z;

            if (deltaY < -3) {

                player.start();
                Location location = new Location("dummyprovider");
                LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
                marker.setPosition(myCoordinates);
                saveToFirebase();
            }

        }
    }
    private void saveToFirebase() {
        Location location = new Location("dummyprovider");
        LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
        Location mCurrentLocation = location;
        Map mLocations = new HashMap();
        Map  mCoordinate = new HashMap();
        mCoordinate.put("Latitude", mCurrentLocation.getLatitude());
        mCoordinate.put("Longitude", mCurrentLocation.getLongitude());
        mLocations.put("location", mCoordinate);
        String url = "MY-FIREBASE-APP";
        DatabaseReference myFirebaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl(url);
        myFirebaseRef.push().setValue(mLocations);

    }



}

我已经包含了依赖项com.google.firebase:firebase-core:16.0.6 该应用程序停止运行,甚至没有将数据写入Firebase。

0 个答案:

没有答案