【问题标题】:Why does this activity crash when i try to upload to firebase databse?当我尝试上传到 Firebase 数据库时,为什么此活动会崩溃?
【发布时间】:2023-03-05 06:11:01
【问题描述】:

我正在构建一个应用程序来从另一台设备跟踪设备的位置。现在,我面临的问题是,当我尝试将纬度和经度上传到 firebase 数据库时它崩溃了。但是,如果我使用 Toast 来显示纬度和经度,它不会崩溃。

DriverMapsActivity.java

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private GoogleMap mMap;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
String userid;
double lat;
double lon;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_driver_maps);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    SupportMapFragment mapFragment = (SupportMapFragment)
            getSupportFragmentManager()
                    .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);




}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
    }

}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(final Location location) {
    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    LocationManager locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), true);
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Location locations = locationManager.getLastKnownLocation(provider);
    List<String> providerList = locationManager.getAllProviders();
    if (null != locations && null != providerList && providerList.size() > 0) {
        double longitude = locations.getLongitude();
        double latitude = locations.getLatitude();
        Geocoder geocoder = new Geocoder(getApplicationContext(),
                Locale.getDefault());
        try {
            List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (null != listAddresses && listAddresses.size() > 0) {

                String state = listAddresses.get(0).getAdminArea();
                String country = listAddresses.get(0).getCountryName();
                String subLocality = listAddresses.get(0).getSubLocality();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
    lat = location.getLatitude();
    lon = location.getLongitude();
    mUser = FirebaseAuth.getInstance().getCurrentUser();
    assert mUser != null;
    userid = mUser.getUid();

    mDatabaseReference.child("users").child(userid).child("Latitude").setValue(lat);
    mDatabaseReference.child("users").child(userid).child("Longitude").setValue(lon);

    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
                this);
    }


}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        } else {

            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }
            } else {
                Toast.makeText(this, "permission denied",
                        Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}
}

问题出在这部分

lat = location.getLatitude();
    lon = location.getLongitude();
    mUser = FirebaseAuth.getInstance().getCurrentUser();
    assert mUser != null;
    userid = mUser.getUid();

    mDatabaseReference.child("users").child(userid).child("Latitude").setValue(lat);
    mDatabaseReference.child("users").child(userid).child("Longitude").setValue(lon);

我什至尝试使用 java 类上传值,然后将值传递给该类。`

有人可以帮忙吗?!

日志猫

E/UncaughtException(18714):     at com.oxford.gpstracker.DriverMapsActivity.onLocationChanged(DriverMapsActivity.java:169)
E/UncaughtException(18714):     at com.google.android.gms.internal.zzcdi.zzq(Unknown Source)
E/UncaughtException(18714):     at com.google.android.gms.internal.zzbdw.zzb(Unknown Source)
E/UncaughtException(18714):     at com.google.android.gms.internal.zzbdx.handleMessage(Unknown Source)
E/UncaughtException(18714):     at android.os.Handler.dispatchMessage(Handler.java:102)
E/UncaughtException(18714):     at android.os.Looper.loop(Looper.java:148)
E/UncaughtException(18714):     at android.app.ActivityThread.main(ActivityThread.java:5469)

【问题讨论】:

  • 在此处发布 logcat 以获得更好的帮助
  • 我已经粘贴了 logcat,但它的格式不正确。我不得不把它从我的手机里拿出来。这就是为什么
  • 也添加你的构建 gradle 依赖项
  • 我确定 build.Gradle 是正确的,因为在另一个活动中,我正在向 firebase 数据库添加数据。这可以正常工作,没有任何错误。错误必须在此活动中。

标签: android google-maps firebase firebase-realtime-database firebase-authentication


【解决方案1】:

mDatabaseReference 必须在使用前初始化。您可以在使用前立即进行,如下图或onCreate()

lat = location.getLatitude();
lon = location.getLongitude();
mUser = FirebaseAuth.getInstance().getCurrentUser();
assert mUser != null;
userid = mUser.getUid();

mDatabaseReference = FirebaseDatabase.getInstance().getReference(); // ADDED

mDatabaseReference.child("users").child(userid).child("Latitude").setValue(lat);
mDatabaseReference.child("users").child(userid).child("Longitude").setValue(lon);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2021-09-05
    • 2022-12-29
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多