我正面临一个严重的问题。我想得到纬度和经度,但应用程序异常停止。我不知道为什么。我也接受了清单的许可。请帮助我,任何形式的帮助将受到高度赞赏。感谢
This is my Fragment
public class FragmentThree extends Fragment {
FindLocation Fl;
GPSTracker gps;
public FragmentThree() {
Fl = new FindLocation();
gps = new GPSTracker(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.location, container, false);
Location location = gps.getLocation();
String latLongString = gps.updateWithNewLocation(location);
Toast.makeText(getActivity(), latLongString, Toast.LENGTH_SHORT).show();
return view;
}
}
GpsTracker.java
public class GPSTracker {
Context mContext;
public GPSTracker(Context mContext){
this.mContext = mContext;
}
public Location getLocation(){
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) mContext.getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
return location;
}
public String updateWithNewLocation(Location location) {
String latLongString;
if (location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
}else{
latLongString = "No Location";
}
return latLongString;
}
}
答案 0 :(得分:3)
gps = new GPSTracker(getActivity());
getActivity在实例化时返回null。您必须等到片段附加到Activity
。你应该等到调用onAttach
。如果尚未获取位置,getLastKnownLocation
也返回null