调用虚拟方法 double android.location.Location.getLatitude

Posted

技术标签:

【中文标题】调用虚拟方法 double android.location.Location.getLatitude【英文标题】:Invoking virtual method double android.location.Location.getLatitude 【发布时间】:2019-10-06 12:04:20 【问题描述】:

我真的被这个错误困住了,我已经尝试了我能想到的一切来避免 getLatitude 方法上的 NPE...

有人可以检查我的代码并推荐解决方案吗?

仅当我在 Lat 和 Lng 的某些坐标中硬编码时它才有效,但这不是我想要做的。提前致谢。



CODE

    public class CoPilotMapActivity extends FragmentActivity implements OnMapReadyCallback 

    private static final int REQUEST_CHECK_SETTINGS = 0x1;
    private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
    private static final int REQUEST_FINE_LOCATION = 1;
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
    private static final long FASTEST_INTERVAL = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    private static final String TAG = "";
    private static final long MIN_TIME_BW_UPDATES = 1;
    private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
    private boolean mRequestingLocationUpdates;

    private GoogleMap mMap;
    private GeoFire mGeoFire;
    private LocationRequest locationRequest;
    private LocationCallback locationCallback;
    private Marker currentUser;
    private DatabaseReference myLocationRef;
    private GeoFire geoFire;
    private List<LatLng> dangerousArea;

    private LocationSettingsRequest mLocationSettingsRequest;
    private SettingsClient mSettingsClient;
    private FusedLocationProviderClient mFusedLocationClient;

    private Button mStartUpdatesButton;
    private Button mLogout;
    private Button mRequest;

    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;
    private TextView mLastUpdateTimeTextView;

    private String mLatitudeLabel;
    private String mLongitudeLabel;
    private String mLastUpdateTimeLabel;

    private String mLastUpdateTime;
    private LocationCallback mLocationCallback;
    private Location mCurrentLocation;
    private LatLng mPickupLocationLatLng;
    private LocationManager mLocationManager;
    final CoPilotMapActivity mContext = this;

    Location mLastLocation;
    LocationRequest mLocationRequest;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    private LocationManager locationManager;
    private double mLatitude;
    private double Longitude;
    private boolean isGPSEnabled;
    private boolean isNetworkEnabled;
    private boolean canGetLocation;
    private Object markerDestination;

    public CoPilotMapActivity() 

    

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_co_pilot_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


        //Signout from firebase after declaring button up top
        mLogout = (Button) findViewById(R.id.logout);
        //Call an uber driver
        mRequest = (Button) findViewById(R.id.request);
        mLogout.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Toast.makeText(CoPilotMapActivity.this, "Sign out successful", Toast.LENGTH_SHORT).show();
                FirebaseAuth.getInstance().signOut();
                //To take you to a different page you create an intent
                Intent intent = new Intent(CoPilotMapActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            
        );

        //ACCESS USER'S LOCATION.................................
        Dexter.withActivity(this)
                .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new PermissionListener() 
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) 
                        //Obtain the SupportMapFragment and get notified when map is ready to be used

                        buildLocationRequest();
                        buildLocationCallback();
                        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(CoPilotMapActivity.this);


                        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
                        mapFragment.getMapAsync(CoPilotMapActivity.this);


                    

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) 
                        Toast.makeText(CoPilotMapActivity.this,"You must enable permission", Toast.LENGTH_SHORT).show();
                    

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) 

                    
                ).check();





        //requesting a driver
        //WORK ON THIS PART NULL POINTER EXCEPTION COMING UP ON GETLATITUDE FUNCTION
        mRequest.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                if(location!= null)
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();



                //send request and pinpoint exact location from where customer
                //will be picked up from
                DatabaseReference ref = FirebaseDatabase.getInstance().getReference("customerRequest");
                GeoFire geoFire = new GeoFire(ref);
                geoFire.setLocation(userId, new GeoLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude()),
                        new GeoFire.CompletionListener() 
                            @Override
                            public void onComplete(String key, DatabaseError error) 
                                if(location!= null)
                                    double latitude = location.getLatitude();
                                    double longitude = location.getLongitude();
                                
                                if (error != null)
                                    System.err.println("There was an error saving the location to GeoFire: " + error);
                                else 
                                    System.out.println("Location saved on server successfully!");
                                
                            
                        );

                geoFire.getLocation(userId, new com.firebase.geofire.LocationCallback() 
                    @Override
                    public void onLocationResult(String key, GeoLocation location) 
                        if (location != null) 
                            System.out.println(String.format("The location for key %s is [%f,%f]", key, location.latitude,
                                    location.longitude));
                        else 
                            System.out.println(String.format("There is no location for key %s in GeoFire", key));

                        
                    

                    @Override
                    public void onCancelled(DatabaseError databaseError) 

                    

                );
                //THIS STILL ISN'T BLOODY WORKING RETRIEVING DRIVERS LOCATION WHEN BUTTON IS CALLED SO
                //WHAT TO DO DAMMIT

                //create marker for customers pickup spot
                mPickupLocationLatLng = new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());

                //change text of request button when it is pressed to request driver
                mRequest.setText("Getting your driver...");


            
        );

    


LOGCAT

E/androidRuntime: FATAL EXCEPTION: main
    Process: com.e.friendrides, PID: 18776
    java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at com.e.friendrides.CoPilotMapActivity$3.onClick(CoPilotMapActivity.java:214)
        at android.view.View.performClick(View.java:6663)
        at android.view.View.performClickInternal(View.java:6635)
        at android.view.View.access$3100(View.java:794)
        at android.view.View$PerformClick.run(View.java:26199)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

【问题讨论】:

以为有了这个我就可以了,但仍然无法正常工作 if(location!= null) double latitude = location.getLatitude();双经度 = location.getLongitude(); CoPilotMapActivity.java:214 是哪一行?我假设它是具有mLastLocation.getLatitude() 的那些之一,那么您在哪里设置mLastLocation 我想我明白了... 我只是把 if 语句放在了错误的位置,所以它没有生效。 【参考方案1】:

这就是如何在“getLatitude”方法上不获取 NPE

代码


//requesting a driver
        //WORK ON THIS PART NULL POINTER EXCEPTION COMING UP ON GETLATITUDE FUNCTION
        mRequest.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                if (location != null) 
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                    //check if gps is enabled or not AND TURN IT ON IF IT'S NOT
                    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
                        //Write Function to enable the gps
                        OnGPS();
                    else
                        //If GPS IS ALREADY ON then ...
                        getLocation();
                    
                

                String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
                //send request and pinpoint exact location from where customer
                //will be picked up from
                DatabaseReference ref = FirebaseDatabase.getInstance().getReference("customerRequest");
                GeoFire geoFire = new GeoFire(ref);
                if (mLastLocation != null) 
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    geoFire.setLocation(userId, new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
                

                //THIS STILL ISN'T BLOODY WORKING RETRIEVING DRIVERS LOCATION WHEN BUTTON IS CALLED SO
                //WHAT TO DO DAMMIT

                //create marker for customers pickup spot
                if (location != null) 
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    mPickupLocationLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                    mMap.addMarker((new MarkerOptions().position(mPickupLocationLatLng).title("Pickup Here")));

                        //change text of request button when it is pressed to request driver
                        mRequest.setText("Getting your driver...");
                
            
        );
    

【讨论】:

以上是关于调用虚拟方法 double android.location.Location.getLatitude的主要内容,如果未能解决你的问题,请参考以下文章

尝试在空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”,在下面这一行中显示错误

java中在方法调用的时候返回多个double类型的值应该怎么办?

尝试在空对象引用上调用虚方法'double android.location.Location.getLatitude()'[duplicate]

编写java程序,double tind(int n) 方法功能求2的N次方 程序中调用该方法 输出2的40次方并输出

在C中调用GetModuleHandle并返回函数指针的正确方法

Java中Double的比较?