在找到设备的当前坐标时抛出空指针异常

时间:2017-02-02 17:33:01

标签: java android nullpointerexception illegalstateexception

嘿伙计们我正在尝试使用基于GPS和网络的当前设备的坐标。我正在为API 23测试此代码。但此代码返回NullPointerException。守则如下:

public class AndroidLocationActivity extends Activity {

    Button btnGPSShowLocation;
    Button btnNWShowLocation;

    private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2;

    protected LocationManager locationManager;
    Location location;

    private static final long MIN_DISTANCE_FOR_UPDATE = 10;
    private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_location);
        btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
        btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);

    }

    public void mGPS(View view){
        Location gpsLocation = getLocation(LocationManager.GPS_PROVIDER);
        if (gpsLocation != null) {
            double latitude = gpsLocation.getLatitude();
            double longitude = gpsLocation.getLongitude();
            Toast.makeText(getApplicationContext(), "Mobile Location (GPS): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
        }
        else {
            showSettingsAlert("GPS");
        }
    }

    public void mNW(View view){
        Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
        if (nwLocation != null) {
            double latitude = nwLocation.getLatitude();
            double longitude = nwLocation.getLongitude();
            Toast.makeText(getApplicationContext(), "Mobile Location (NW): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
        }
        else {
            showSettingsAlert("NETWORK");
        }
    }

    public void showSettingsAlert(String provider) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                AndroidLocationActivity.this);

        alertDialog.setTitle(provider + " SETTINGS");

        alertDialog.setMessage(provider + " is not enabled! Want to go to settings menu?");

        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        AndroidLocationActivity.this.startActivity(intent);
                    }
                });

        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        alertDialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

            }
            else {
                locationManager.requestLocationUpdates(provider, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, (LocationListener) this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider);
                    return location;
                }
            }
        }
        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 ) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                        Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();

                    }
                    else if(grantResults[0]==PackageManager.PERMISSION_DENIED) {
                        Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                    }
                    else {

                        Toast.makeText(this, "Never Ask Again", Toast.LENGTH_SHORT).show();
                    }
                }
                return;
            }
        }
    }
}

守则返回以下错误:

  

致命的例外:主要                     过程:com.cetpainfotech.locationtrackerapplication,PID:29068                     java.lang.IllegalStateException:无法执行android:onClick的方法                         在android.view.View $ DeclaredOnClickListener.onClick(View.java:4461)                         在android.view.View.performClick(View.java:5207)                         在android.view.View $ PerformClick.run(View.java:21177)                         在android.os.Handler.handleCallback(Handler.java:739)                         在android.os.Handler.dispatchMessage(Handler.java:95)                         在android.os.Looper.loop(Looper.java:148)                         在android.app.ActivityThread.main(ActivityThread.java:5441)                         at java.lang.reflect.Method.invoke(Native Method)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:738)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)                      引起:java.lang.reflect.InvocationTargetException                         at java.lang.reflect.Method.invoke(Native Method)                         在android.view.View $ DeclaredOnClickListener.onClick(View.java:4456)                         在android.view.View.performClick(View.java:5207)                         在android.view.View $ PerformClick.run(View.java:21177)                         在android.os.Handler.handleCallback(Handler.java:739)                         在android.os.Handler.dispatchMessage(Handler.java:95)                         在android.os.Looper.loop(Looper.java:148)                         在android.app.ActivityThread.main(ActivityThread.java:5441)                         at java.lang.reflect.Method.invoke(Native Method)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:738)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)                      引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)'                         at com.cetpainfotech.locationtrackerapplication.AndroidLocationActivity.getLocation(AndroidLocationActivity.java:108)                         在com.cetpainfotech.locationtrackerapplication.AndroidLocationActivity.mGPS(AndroidLocationActivity.java:52)                         at java.lang.reflect.Method.invoke(Native Method)                         在android.view.View $ DeclaredOnClickListener.onClick(View.java:4456)                         在android.view.View.performClick(View.java:5207)                         在android.view.View $ PerformClick.run(View.java:21177)                         在android.os.Handler.handleCallback(Handler.java:739)                         在android.os.Handler.dispatchMessage(Handler.java:95)                         在android.os.Looper.loop(Looper.java:148)                         在android.app.ActivityThread.main(ActivityThread.java:5441)                         at java.lang.reflect.Method.invoke(Native Method)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:738)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

我的条件是,如果函数getLocation()返回null,那么它将显示一个警告对话框。相反,当我点击按钮时,它显示空指针异常。

我已经在XML文件中注册了onClick方法(mGPS和mNW)。

2 个答案:

答案 0 :(得分:2)

  

但我的问题是,尽管mGPS()和mNW()中的else条件用于处理null,但此代码抛出异常

您的异常是throw ,因为if语句已被评估该变量为null。

if (locationManager.isProviderEnabled(provider)) {

这是一个正确的空检查。

if (locationManager != null && locationManager.isProviderEnabled(provider)) {

} else {

}

您应该实际初始化变量,并在onCreate

中添加这样的行
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);

答案 1 :(得分:0)

您没有初始化locationManager,因此当您致电locationManager.isProviderEnabled(provider)时,NullPointerException

失败

这显示在您的堆栈跟踪中,就在这里

  

引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)'