简体   繁体   English

将字符串从活动传递到片段

[英]Passing String From Activity to Fragment

My Activty code snippet is which implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener : 我的活动代码段实现了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);
    }
}

All I want is to get the String Latitude and longitude in my fragment ie 我想要的只是获取片段中的字符串纬度和经度,即

@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);
}

I am getting NPE in this line ie 我在这一行中获得NPE,即

 Log.wtf("check","Latitude"+((MyActivuty)getActivity()).latitude+
"Longitude"+((MyActivuty)getActivity()).longitude);

because onComplete Method is called after fragment's OnCreate().HOw Can i solve this problem? 因为onComplete方法是在片段的OnCreate()之后调用的。我该如何解决这个问题? Any help appreciated!Thanks 任何帮助表示感谢!

Create a callback function inside of the fragment: 在片段内部创建一个回调函数:

public void initFragment() {
    // Coordinates are available do something with them
    // ((MyActivuty)getActivity()).latitude
    // ((MyActivuty)getActivity()).longitude
}

Then in your activity save a reference to the create fragment: 然后在您的活动中保存对创建片段的引用:

MyFrag myFrag
...
myFrag = new MyFrag();
...

And call your fragment's function when the coordinates are ready: 并在坐标准备好后调用片段的函数:

public void getCurrentLocation() {
    ...
    myFrag.initFragment();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM