0

I want to get the value of mLocal in my Activity and pass it to LatLng on Fragment class.

Main Activity

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            initLocationFetching(MainActivity.this);

        mapFragment = new MapFragment(MainActivity.this, this);
        manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.mainLayout, mapFragment).commit();
}
            @Override
        public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
        super.locationFetched(mLocal, oldLocation, time, locationProvider);
    > here mLocal
    }

Map Fragment Class

 class MapFragment extends Fragment implements OnMapReadyCallback,
            GoogleApiClient.OnConnectionFailedListener {

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        LatLng origin = new LatLng(14.507328, 121.000905);

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(14.507577, 121.004456))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(value1, value2), 9.0f));

    }

Above, I want it not hardcoded. I want to get the value of mLocal in MainActivity and pass it on LatLng() MapFragment.

user8256287
  • 177
  • 15
  • Possible duplicate of [How to send string from one activity to another?](https://stackoverflow.com/questions/18146614/how-to-send-string-from-one-activity-to-another) – Soham Jul 24 '17 at 06:03
  • Hi Soham, I want to get the value of Location on my MainActivity and pass it to Fragment Activity where LatLng value is required for mapping. Do you have any clue? – user8256287 Jul 24 '17 at 06:05
  • Does `locationFetched()` get called before `onMapReady()`? The clean way of doing this would be for your parameter to be available when `onMapReady()` gets called. – Tim Biegeleisen Jul 24 '17 at 06:06
  • I believe because I called it first on MainActivity's onCreate – user8256287 Jul 24 '17 at 06:11
  • Is MapFragment in MainActivity? – MidasLefko Jul 24 '17 at 06:14
  • Yep, Here's how I called the two `initLocationFetching(MainActivity.this); mapFragment = new MapFragment(MainActivity.this, this); manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, mapFragment).commit();` – user8256287 Jul 24 '17 at 06:16

6 Answers6

1

you can take a public global vaiable of Location in activity and create it's getter-setter

 

 MainActivity extends Activity

    public Location mLocal;
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            @Override
        public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
        super.locationFetched(mLocal, oldLocation, time, locationProvider);
    setMLocal(mLocal);
    } 
     public String getMLocal() {
            return mLocal;
        }

        public void setMLocal(String mLocal) {
            this.mLocal= mLocal;
        }

And then you can use getter method in your fragment

public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    Location mLocal = ((MainActivity)getActivity).getMLocal(); //you can get your Location object and you can use it further
        //LatLng origin = new LatLng(14.507328, 121.000905);

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(14.507577, 121.004456))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));

  • Hi Sonal, `public String` is invalid mLocal is Location and cannot resolve at getActivity `((MainActivity)getActivity)` the class is fragment. – user8256287 Jul 24 '17 at 06:35
  • Also, I am having a null pointer here `Location mLocal = ((MainActivity)activity).getMLocal();` `LatLng origin = new LatLng(mLocal.getLatitude(), mLocal.getLongitude());` – user8256287 Jul 24 '17 at 06:43
  • please take public Location mLocal; not string i have mentioned in code, you can direct get Location object in your fragment. And your MapFragment is part of your MainActivity only,right? – Sonal Bharwani Jul 24 '17 at 06:46
  • Make sure your frangment is being switched after onLocationFetched is called beacause in onLocationFetched value is set to the global variable of Location. – Sonal Bharwani Jul 24 '17 at 07:20
  • Hi Sonal, pls. provide solution. Thanks. – user8256287 Jul 24 '17 at 07:24
  • can you show me where do write your code of replacing fragment? – Sonal Bharwani Jul 24 '17 at 08:14
0

You can add a method to MapFragment called setLocation and call it in MainActivity.

Like this:

MapFragment

// Location mCurrentLoc = null;

public void setLocation(Location loc) {
    mCurrentLoc = loc;
    if (mMap != null) {
        //do fragment location stuff
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    // all your above code

    if (mCurrentLocation != null) {
        // do fragment location stuff
    }
}

MainActivity

mapFragment.setLocation(mLocal);
MidasLefko
  • 4,499
  • 1
  • 31
  • 44
  • you probably have a race between map and location (which is really another question altogether) but I added more to the example code to help you. – MidasLefko Jul 24 '17 at 07:27
0

To pass data from activity to fragment you can use Bundle to put your variable and set fragment's argument with this Bundle or you can use another way (I don't see your whole project to get sure its the better way) EventBus

BNAndroid
  • 158
  • 4
  • Ok, so I suggest you to use EventBus (or a local broadcastReceiver), and post an event from within the onMapReady() and catch that event from your activity and when event catched call your member set value.(because at this point you know that map is ready) – BNAndroid Jul 24 '17 at 06:39
0

You have the instance of MapFragment as mapFragment right?

So create a public method in MapFragment.class as getCoordinates

    public void getCoordinates(double latitude, double longitude){
         this.latitude = latitude;
         this.longitude = longitude;
}

Send coordinates from Activity to fragment as below

if(mapFragment instanceOf MapFragment){
 ((MapFragment)mapFragment).getCoordinates(latitude, longitude);
Sai's Stack
  • 1,345
  • 2
  • 16
  • 29
0
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initLocationFetching(MainActivity.this);

    mapFragment = new MapFragment(MainActivity.this, this);
    manager = getSupportFragmentManager();
}
 @Override
    public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
    super.locationFetched(mLocal, oldLocation, time, locationProvider);
 //After initLocationFetching.
 Bundle bundle = new Bundle();
 bundle.putDouble("Lat",mLocal.getLatitude());
 bundle.putDouble("Long"mLocal.getLongitude());
 mapFragment.setArguments(bundle);
 manager.beginTransaction().replace(R.id.mainLayout, mapFragment).commit();
}



//In MapFragment
class MapFragment extends Fragment implements OnMapReadyCallback,
        GoogleApiClient.OnConnectionFailedListener {
double lati=0.0;
double longi=0.0;

@Override
public void onCreate(Bundle bundle){
lati=getArguments().getDouble("Lat");
longi=getArguments().getDouble("Long");
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    LatLng origin = new LatLng(lati,longi);

    mMap.addMarker(new MarkerOptions()
            .position(new LatLng(lati,longi))
            .anchor(0.5f, 0.5f)
            .title("title")
            .snippet("snippet")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(value1, value2), 9.0f));

}
Santhosh
  • 160
  • 7
0

You must create an instance of your activity and thus pass the data of it to your fragment

In your fragment, Declare a variable of your MainActivity to obtain the context of it and thus be able to work with it on the fragment and declares the variable to which you want to assign the value that it contains in the MainActivity and pass the value on the onAttach method. onAttch is called when a fragment is first attached to its context.

private MainActivity mActivity;
private String mData;

Now in the onAttach method that is when the fragment adheres to its container which is the main activity.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    //Verify if mActivity is null and it is MainActivity context
    if (mActivity == null && context instanceof MainActivity) {
        mActivity = (MainActivity) getActivity();
        //Checking for a NPE       
        if(mActivity != null){
         mData = mActivity.MyMainActivityVariable;
       }
     }
   }

And in the onDetach method Called when the fragment is no longer attached to its activity.

@Override
public void onDetach() {
    super.onDetach();
    mActivity = null;
    }

Now we can work with the variable we want to use from the MainActivity. This is using Support Library Fragment For more info about Fragments go to Fragment Android Developers

Quimbo
  • 634
  • 6
  • 17