首页 > 解决方案 > 如何手动设置位置中的纬度和经度?

问题描述

我试图在应用程序中手动设置纬度和经度但是,运行后给我一个错误

代码

public class Common {

    public static Location NewYork;
}

配置

public void setLocation(){
    Common.NewYork.setLatitude(31.963158);  //error in this Line <--
    Common.NewYork.setLongitude(35.930359);
   fragmentAdapter();
}

错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.Location.setLatitude(double)' on a null object reference

标签: javaandroid

解决方案


您从未初始化NewYork变量,因此在setLocation()调用时将其设置为 null。您可以通过以下方式更改:

public class Common {
    // Create new Location with an empty provider name, it's not necessary here
    public static Location NewYork = new Location(""); 
}

或者

public void setLocation() {
    Common.NewYork = new Location(""); 
    ...
}

推荐阅读