Java 我一直得到一个位置为空的错误

Java 我一直得到一个位置为空的错误,java,android,firebase,geofire,Java,Android,Firebase,Geofire,我正在开发一个应用程序,它有一个名为postar的方法,调用该方法时应创建一个数据库引用,并将一个子项添加到我的Firebase Consoles贷方表中,该子项包含用户id和位置。问题是位置一直被标记为空。我的PostCar方法中的代码读取“geoFire.setLocation(userId,new GeoLocation(mlastlocation.getLatitude(),mlastlocation.getLatitude());“不断抛出错误”尝试在空对象引用上调用虚拟方法“doub

我正在开发一个应用程序,它有一个名为postar的方法,调用该方法时应创建一个数据库引用,并将一个子项添加到我的Firebase Consoles贷方表中,该子项包含用户id和位置。问题是位置一直被标记为空。我的PostCar方法中的代码读取“geoFire.setLocation(userId,new GeoLocation(mlastlocation.getLatitude(),mlastlocation.getLatitude());“不断抛出错误”尝试在空对象引用上调用虚拟方法“double android.location.location.getLatitude()”。设备位置已打开,我检查位置权限。下面是代码


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

包com.example.movir;
导入androidx.appcompat.app.appcompat活动;
导入androidx.core.app.ActivityCompat;
导入androidx.core.content.ContextCompat;
导入android.Manifest;
导入android.app.AlertDialog;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.pm.PackageManager;
导入android.location.location;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.os.Looper;
导入android.view.view;
导入android.widget.Button;
导入android.widget.Toast;
导入com.firebase.geofire.geofire;
导入com.firebase.geofire.GeoLocation;
导入com.google.android.gms.location.FusedLocationProviderClient;
导入com.google.android.gms.location.LocationCallback;
导入com.google.android.gms.location.LocationRequest;
导入com.google.android.gms.location.LocationResult;
导入com.google.android.gms.location.LocationServices;
导入com.google.android.gms.maps.model.LatLng;
导入com.google.android.gms.tasks.OnSuccessListener;
导入com.google.firebase.auth.FirebaseAuth;
导入com.google.firebase.auth.FirebaseUser;
导入com.google.firebase.database.DatabaseReference;
导入com.google.firebase.database.FirebaseDatabase;
公共类LendersMenuPageActivity扩展了AppCompativeActivity{
私有字符串用户标识;
私人消防队;
私人位置经理lm;
位置mlastlocation;
位置请求位置请求;
LocationCallback LocationCallback;
私人按钮;
最终LendCarForm cardlend=新LendCarForm(用户ID,“全新丰田”、“丰田”、“凯美瑞S9”);
私有FusedLocationProviderClient fusedLocationClient;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u菜单\u页面);
mAuth=FirebaseAuth.getInstance();
fusedLocationClient=LocationServices.getFusedLocationProviderClient(此);
fusedLocationClient.getLastLocation()文件
.addOnSuccessListener(此,新的OnSuccessListener(){
@凌驾
成功时的公共无效(位置){
//已获取最后一个已知位置。在某些罕见情况下,此值可以为空。
如果(位置!=null){
//处理位置对象的逻辑
}
}
});
FirebaseUser currentUser=mAuth.getCurrentUser();
userId=currentUser.getUid();
DatabaseReference lendersReference=FirebaseDatabase.getInstance().getReference(“用户”).child(“贷款人”).child(用户ID);
lendcarButton=findviewbyd(R.id.car\u按钮);
setOnClickListener(onClick);
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION\u服务);
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
考虑到呼叫
//ActivityCompat#请求权限
//在此处请求缺少的权限,然后覆盖
//public void onRequestPermissionsResult(int-requestCode,字符串[]权限,
//int[]格兰特结果)
//处理用户授予权限的情况。请参阅文档
//对于ActivityCompat,请请求权限以获取更多详细信息。
返回;
}
LocationCallback LocationCallback=新LocationCallback(){
@凌驾
public void onLocationResult(LocationResult LocationResult){
对于(位置:locationResult.getLocations()){
如果(getApplicationContext()!=null){
mlastlocation=位置;
LatLng LatLng=新LatLng(location.getLatitude(),location.getLongitude());
}
}
}
};
mlastlocation=lm.getLastKnownLocation(LocationManager.GPS\U提供程序);
}
@凌驾
受保护的void onStart(){
super.onStart();
checkLocationPermission();
}
private void startLocationUpdates(){
fusedLocationClient.RequestLocationUpdate(locationRequest,
位置回调,
getMainLooper());
}
public View.OnClickListener onClick=new View.OnClickListener(){
@凌驾
公共void onClick(视图v){
Toast.makeText(LendersMenuPageActivity.this,“hello”,Toast.LENGTH\u LONG);
postar();
}
};
私有void checkLocationPermission(){
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予){
if(ActivityCompat.shouldshowRequestPermissionRegulation(这是Manifest.permission.ACCESS\u FINE\u位置)){
新建AlertDialog.Builder(此)
.setTitle(“给予许可”)
.setMessage(“授予权限消息”)
.setPosit