我正在制作一个需要在继续之前找到用户的 GPS 位置的应用程序。我通过实现 LocationListener 接口来做到这一点。
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(loc!=null){
loc.getLatitude();
loc.getLongitude();
text = "My current location is: " + "Latitude = " + loc.getLatitude() + "Longitude = " + loc.getLongitude();
Toast.makeText(getApplicationContext(),text, Toast.LENGTH_SHORT).show();
}
}
但是我在 getApplicationContext() 方法中得到了 NullPointerException。我也尝试了 MyClass.this,但结果相同。当我在 onCreate 中显示吐司时,吐司工作正常。我查找了与此类似的其他问题,但没有一个解决方案有效。我在 onCreate 中使用 setContentView,如下所示:
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gpslocation);
}
logcat 显示了这一点:
03-14 14:05:48.396: E/AndroidRuntime(604): FATAL EXCEPTION: main
03-14 14:05:48.396: E/AndroidRuntime(604): java.lang.NullPointerException
03-14 14:05:48.396: E/AndroidRuntime(604): at emergency.app.MyLocationListener.onLocationChanged(MyLocationListener.java:53)
03-14 14:05:48.396: E/AndroidRuntime(604): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:227)
03-14 14:05:48.396: E/AndroidRuntime(604): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:160)
03-14 14:05:48.396: E/AndroidRuntime(604): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:176)
03-14 14:05:48.396: E/AndroidRuntime(604): at android.os.Handler.dispatchMessage(Handler.java:99)
03-14 14:05:48.396: E/AndroidRuntime(604): at android.os.Looper.loop(Looper.java:137)
03-14 14:05:48.396: E/AndroidRuntime(604): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-14 14:05:48.396: E/AndroidRuntime(604): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 14:05:48.396: E/AndroidRuntime(604): at java.lang.reflect.Method.invoke(Method.java:511)
03-14 14:05:48.396: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-14 14:05:48.396: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-14 14:05:48.396: E/AndroidRuntime(604): at dalvik.system.NativeStart.main(Native Method)
有人能告诉我如何克服这个吗?我是android的初学者,所以我真的需要帮助!