我的 Activty 代码 fragment 实现了 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);
}
}
我想要的只是在我的 fragment 中获取字符串纬度和经度
@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 ie
Log.wtf("check","Latitude"+((MyActivuty)getActivity()).latitude+
"Longitude"+((MyActivuty)getActivity()).longitude);
因为 onComplete 方法是在 fragment 的 OnCreate() 之后调用的。我该如何解决这个问题? 任何帮助表示赞赏!谢谢
最佳答案
在 fragment 中创建一个回调函数:
public void initFragment() {
// Coordinates are available do something with them
// ((MyActivuty)getActivity()).latitude
// ((MyActivuty)getActivity()).longitude
}
然后在您的 Activity 中保存对创建 fragment 的引用:
MyFrag myFrag
...
myFrag = new MyFrag();
...
并在坐标准备就绪时调用 fragment 的函数:
public void getCurrentLocation() {
...
myFrag.initFragment();
}
关于java - 将字符串从 Activity 传递到 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25604797/