为什么我的Android应用程序中出现“java.lang.NullPointerException”?

时间:2016-01-15 13:12:42

标签: android nullpointerexception

我想在屏幕上显示“hello”消息但我的应用程序无效。

导致“java.lang.NullPointerException”的原因是什么?

调试器表示经度值为null。即使是这种情况,我的“你好”消息是否仍然不会出现?

我有以下代码:

 package autogenie.maptrial;

 import android.Manifest;

 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.location.Location;
 import android.location.LocationManager;
 import android.support.v4.app.ActivityCompat;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private Location location;
private Double latitude, longitude;
private LocationManager locationManager;


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

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


    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    longitude=location.getLongitude();
    latitude=location.getLatitude();



    Context context = getApplicationContext();
    String s="hello";
    int duration = Toast.LENGTH_LONG;

    Toast toast = Toast.makeText(context,s, duration);
    toast.show();


}
}

调试器显示的内容:

Screenshot of debugger

之后它崩溃了。

4 个答案:

答案 0 :(得分:2)

替换

longitude=location.getLongitude();
latitude=location.getLatitude();

if( location != null ) {
    longitude=location.getLongitude();
    latitude=location.getLatitude();
}

您尝试调用方法调用的longitude字段不是null,而是location字段。这会产生异常。当您如上所述替换代码时,您将使程序无故障地运行。

答案 1 :(得分:0)

请检查是否启用了GPS_Provider。看起来GPS没有启用,你尝试使用它。在这种情况下,location将为null

答案 2 :(得分:0)

添加以下检查 -

if(location != null){
    longitude=location.getLongitude();
    latitude=location.getLatitude();
}

答案 3 :(得分:0)

位置实例上设置条件,如果它不为空,则只进行。

您应该使用FusedLocationProviderApi根据Android文档获取当前位置。在此处阅读更多内容:Getting the Last Known Location