1

My Activty code snippet is which implements 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

 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? Any help appreciated!Thanks

williamj949
  • 11,166
  • 8
  • 37
  • 51

1 Answers1

2

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();
}
Simas
  • 43,548
  • 10
  • 88
  • 116
  • Thanks this worked for me. @user3249477 please do you think you could give me your opinion on this question http://stackoverflow.com/questions/25598696/recommended-way-order-to-read-data-from-a-webservice-parse-that-data-and-inse – Axel Sep 02 '14 at 03:27
  • sure it does work.But i my case i was using multiple fragments which i was creating using a adapter,instead of using a single fragment – williamj949 Sep 02 '14 at 06:30