我的Activty代码段实现了GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
:
@Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
}
public void getCurrentLocation() {
if (this.servicesConnected()) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
mCurrentLocation = mLocationClient.getLastLocation();
ArrayList<Address> addresses = null;
try {
latitude = String.valueOf(mCurrentLocation.getLatitude());
longitude = String.valueOf(mCurrentLocation.getLongitude());
addresses = (ArrayList<Address>) gCoder.
getFromLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), 1);
mLocationClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
Log.wtf("Arsnal", "" + addresses.get(0).getLocality());
} else {
Toast.makeText(this, R.string.no_address_found, Toast.LENGTH_LONG).show();
}
Log.wtf("Location", "Lat " + latitude + " - lon " + longitude);
}
}
我想要的只是在片段中获得字符串纬度和经度,即
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.wtf("check","Inside OnCreate of Fragment!");
Log.wtf("check","Latitude"+((MyActivuty)getActivity()).latitude+
"Longitude"+((MyActivuty)getActivity()).longitude);
}
我在这条线上获得了NPE,即
Log.wtf("check","Latitude"+((MyActivuty)getActivity()).latitude+
"Longitude"+((MyActivuty)getActivity()).longitude);
因为onCmplete方法是在片段的OnCreate()之后调用的。我可以解决这个问题吗? 任何帮助表示感谢!谢谢
答案 0 :(得分:2)
在片段内创建一个回调函数:
public void initFragment() {
// Coordinates are available do something with them
// ((MyActivuty)getActivity()).latitude
// ((MyActivuty)getActivity()).longitude
}
然后在您的活动中保存对创建片段的引用:
MyFrag myFrag
...
myFrag = new MyFrag();
...
在坐标准备就绪时调用片段的函数:
public void getCurrentLocation() {
...
myFrag.initFragment();
}