无法在 OnMapReady (Android Studio) 中获取 getter 的值

Cannot get value of getter in OnMapReady (Android Studio)

我正在尝试通过指向 Google 地图来获取实时位置。目前我成功地实时获取了纬度和经度,它每次都会更新为 getter、setter class 称为 sosrecord.getLatitude()sosrecord.getLongitude()。我想根据更新的经纬度指向 google 地图。但是每次当我把 getter 放在 LatLng latLng = new LatLng(sosrecord.getLatitude(), sosrecord.getLongitude()); 上时,它都会 return me Null 并最终使应用程序崩溃,因为 java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference 当用户点击一个时它应该指向当前位置按钮。抱歉,如果下面的代码示例很乱,希望有人能帮助我解决这个问题。谢谢。

Main.java

public class MainActivity extends FragmentActivity{
    private Handler mHandler = new Handler();
    DatabaseReference reff;
    SosRecords sosrecords;
    boolean startclicked =true;
    String selectedOfficer = "Police";
    private static final String TAG = "MainActivity";
    int LOCATION_REQUEST_CODE = 1001;
    SupportMapFragment smf;



    FusedLocationProviderClient fusedLocationProviderClient;
    LocationRequest locationRequest; 
    LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult   <------This function will get the lat and long and set the value to sosrecordlocationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                sosrecords.setLatitude(lat);
                sosrecords.setLongitude(lon);

            }
        }
    };


    private void showOptionDialog() {
        String[] officers = {"Police", "Hospital", "Bomba"};
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Choose SOS types");
        builder.setSingleChoiceItems(officers, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                selectedOfficer = officers[which];
            }
        });
        builder.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                sosrecords.setCallFor(selectedOfficer);{
                    onStart();
                    startclicked= false;
                    //GET ALL INFORMATION FROM FIRESTORE AND SEND TO REALTIME DATABASE
                    if(FirebaseAuth.getInstance().getCurrentUser()!= null){
                        DocumentReference df = FirebaseFirestore.getInstance().collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid());
                        df.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                            @Override
                            public void onSuccess(DocumentSnapshot documentSnapshot) {
                                if(documentSnapshot.getString("FullName")!= null){
                                    String id = reff.push().getKey();
                                    Log.d(TAG, "asdasd"+id);
                                    SosRecords sosRecords = new SosRecords(documentSnapshot.getString("FullName"), (documentSnapshot.getString("PhoneNumber")), (documentSnapshot.getString("UserEmail") ),sosrecords.getLatitude(),sosrecords.getLongitude(),sosrecords.getCallFor() );
                                    reff.child(id).setValue(sosRecords);
                                    sosrecords.setRecordID(id);
                                    btnStartSOS.setEnabled(false);
                                    btnStopSOS.setEnabled(true);
                                    Toast.makeText(MainActivity.this, "You're are now activating SOS request !", Toast.LENGTH_SHORT).show();
                                    LatLonLoop.run();
                                    smf.getMapAsync(new OnMapReadyCallback() {
                                        @Override
                                        public void onMapReady(GoogleMap googleMap) {
                                            LatLng latLng = new LatLng(sosrecords.getLatitude(),sosrecords.getLongitude());
                                            MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Here");

                                            googleMap.addMarker(markerOptions);
                                            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
                                        }
                                    });

                                }

                            }


                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                FirebaseAuth.getInstance().signOut();
                                startActivity(new Intent(getApplicationContext(),Login.class));
                                finish();
                            }
                        });
                    }
                    if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
                        checkSettingsAndStartLocationUpdates();
                    }else{
                        askLocationPermission();
                    }


                }
                dialog.dismiss();
            }
        });

我的get/setclass

package com.example.sossystem;

public class SosRecords {

    String RecordID;
    String FullName;
    String PhoneNumber;
    String EmailAddress;
    Double Latitude;
    Double Longitude;
    String CallFor;


    public SosRecords(){

    }



    public SosRecords(String fullName, String phoneNumber, String userEmail, Double latitude, Double longitude, String callFor) {

        FullName = fullName;
        PhoneNumber = phoneNumber;
        EmailAddress = userEmail;
        Latitude = latitude;
        Longitude = longitude;
        CallFor = callFor;
    }

    public String getRecordID() {
        return RecordID;
    }

    public void setRecordID(String recordID) {
        RecordID = recordID;
    }

    public String getFullName() {
        return FullName;
    }

    public void setFullName(String fullName) {
        FullName = fullName;
    }

    public String getPhoneNumber() {
        return PhoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        PhoneNumber = phoneNumber;
    }

    public String getEmailAddress() {
        return EmailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        EmailAddress = emailAddress;
    }

    public Double getLatitude() {
        return Latitude;
    }

    public void setLatitude(Double latitude) {
        Latitude = latitude;
    }

    public Double getLongitude() {
        return Longitude;
    }

    public void setLongitude(Double longitude) {
        Longitude = longitude;
    }

    public String getCallFor() {
        return CallFor;
    }

    public boolean setCallFor(String callFor) {
        CallFor = callFor;
        return false;
    }
}



问题是,当您打开 MainActiity 时,onMapReady()LocationCallback 之前首先自动调用。最终,它将 return 空纬度和经度。

但是,您的问题是您尚未分配地图片段。

首先,你需要在for循环下面的onLocationResult()中赋值。

 SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
 supportMapFragment.getMapAsync(MapsActivity.this);

其次, 从 onMapReady() 中删除 smf.getMapAsync()。

而不是

smf.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(sosrecords.getLatitude() 
                          ,sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions(). 
                              position(latLng).title("Here");

googleMap.addMarker(markerOptions);
                                        
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});

替换,

// declare googlemap as a globally
private GoogleMap mMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(sosrecords.getLatitude() 
                          ,sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions(). 
                              position(latLng).title("Here");

googleMap.addMarker(markerOptions);
                                        
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});