简体   繁体   中英

i keep getting an error that location is null

I am working on an app that has a method called PostCar that when called should create a databasereference and add a child to My Firebase Consoles Lender table a child that contains the user's id and location. The problem is the location keeps getting marked as null. The code in my PostCar method that reads "geoFire.setLocation(userId,new GeoLocation(mlastlocation.getLatitude(),mlastlocation.getLongitude()));" keeps throwing the error "attempt to invoke virtual method 'double android.location.location.getlatitude()' on a null object reference". The devices location is on and I check for location permissions. Here is the code below.


package com.example.movir;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class LendersMenuPageActivity extends AppCompatActivity {

    private String userId;
    private FirebaseAuth mAuth;
    private LocationManager lm;
     Location mlastlocation;
    LocationRequest locationRequest;
    LocationCallback locationCallback;


    private Button lendcarButton;
    final LendCarForm cardlend = new LendCarForm(userId,"brand new Toyota","Toyota","Camry S9");
    private FusedLocationProviderClient fusedLocationClient;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lenders_menu_page);


        mAuth = FirebaseAuth.getInstance();
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        fusedLocationClient.getLastLocation()
                .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // Got last known location. In some rare situations this can be null.
                        if (location != null) {
                            // Logic to handle location object
                        }
                    }
                });



        FirebaseUser currentUser = mAuth.getCurrentUser();
        userId = currentUser.getUid();
        DatabaseReference lendersReference = FirebaseDatabase.getInstance().getReference("Users").child("Lenders").child(userId);
         lendcarButton = findViewById(R.id.lenders_car_button);
         lendcarButton.setOnClickListener(onClick);
        LocationManager lm = (LocationManager) getSystemService(Context.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;
        }
        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                for (Location location : locationResult.getLocations()) {

                    if(getApplicationContext()!=null) {
                        mlastlocation = location;
                        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());



                    }
                }
            }
        };
        mlastlocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);






    }

    @Override
    protected void onStart() {
        super.onStart();
        checkLocationPermission();
    }

    private void startLocationUpdates() {
        fusedLocationClient.requestLocationUpdates(locationRequest,
                locationCallback,
                Looper.getMainLooper());
    }
    public View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
         Toast.makeText(LendersMenuPageActivity.this,"hello",Toast.LENGTH_LONG);
            postCar();
        }
    };

private void checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            new AlertDialog.Builder(this)
                    .setTitle("give permission")
                    .setMessage("give permission messaage")
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(LendersMenuPageActivity.this, new String[]{
                                    Manifest.permission.ACCESS_FINE_LOCATION
                            }, 1);
                        }
                    })
                    .create()
                    .show();

        } else {
            ActivityCompat.requestPermissions(LendersMenuPageActivity.this, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, 1);
        }



    }
}

    public void postCar(){

       DatabaseReference carsForRent = FirebaseDatabase.getInstance().getReference("Users").child("Lenders").child(userId);

       GeoFire geoFire = new GeoFire(carsForRent);
     geoFire.setLocation(userId,new GeoLocation(mlastlocation.getLatitude(),mlastlocation.getLongitude()));

       carsForRent.setValue(cardlend);
    }
}

Are you testing this with the Xcode IOS simulator? The simulator can't actually access your real location so when queried it will return null unless specified manually (Features tab, Location, Custom Location.)

The reason fusedapi was not working for me is because i was not using a google maps project. So I overode onlocatiochanged instead. This worked for me, but you have to extend onlcationchanged and googleapi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM