How to make communication between ParentFragment and Appolica Interactive InfoWindow Fragment - android

I tried to use callback to communicate between my fragments but it seems that infowindowfragment does not recognize my mapFragment as its parentfragment, is there something I can do to work or have another way to do this?
Mapfragment (parentFragment):
public class MapFragment extends Fragment implements MapView, OnMapReadyCallback, //GoogleMap.InfoWindowAdapter,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
,InfoWindowFragment.OnChildFragmentInteractionListener{
...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mapInfoWindowFragment =
(MapInfoWindowFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapInfoWindowFragment.getMapAsync(this);
}
...
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
setOnMakerClick(map);
moveCameraToLastKnowLocation();
}
...
public void setOnMakerClick(final GoogleMap googleMap){
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
NearDriver nearDriver = markers.get(marker);
LatLng position = new LatLng(nearDriver.getLatitude()+0.007, nearDriver.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
//marker.showInfoWindow();
final int offsetX = (int) getResources().getDimension(R.dimen.marker_offset_x);
final int offsetY = (int) getResources().getDimension(R.dimen.marker_offset_y);
final InfoWindow.MarkerSpecification markerSpec =
new InfoWindow.MarkerSpecification(offsetX, offsetY);
InfoWindowFragment infoWindowFragment = new InfoWindowFragment();
final InfoWindow infoWindow = new InfoWindow(marker, markerSpec, infoWindowFragment);
mapInfoWindowFragment.infoWindowManager().toggle(infoWindow, true);
infoWindowFragment.render(nearDriver);
return true;
}
});
}
...
#Override
public void messageFromChildToParent(Place place) {
Log.d("d", "MapFragment - Place: " + place.getName());
setOnMakerClick(map);
}
InfoWindowFragment ("ChildFragment"):
public interface OnChildFragmentInteractionListener {
void messageFromChildToParent(Place place);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// check if parent Fragment implements listener
if (getParentFragment() instanceof OnChildFragmentInteractionListener) {
mParentListener = (OnChildFragmentInteractionListener) getParentFragment();
} else {
throw new RuntimeException("The parent fragment must implement OnChildFragmentInteractionListener");
}
}
Logcat:
06-13 00:53:57.427 18791-18791/com.rsm.yuri.projecttaxilivre E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rsm.yuri.projecttaxilivre, PID: 18791
java.lang.RuntimeException: The parent fragment must implement OnChildFragmentInteractionListener
at com.rsm.yuri.projecttaxilivre.map.InteractiveInfoWindow.InfoWindowFragment.onAttach(InfoWindowFragment.java:175)

I solved this problem by changing the way to access the mapfragment:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) context;
MapFragment parentFragment = mainActivity.getMapFragment();
if (parentFragment != null) {
mParentListener = (OnChildFragmentInteractionListener) parentFragment;
} else {
throw new RuntimeException("The parent fragment must implement OnChildFragmentInteractionListener");
}
}
}

Related

Add markers on Google Map in other Fragment

How to get access from main activity to fragment? I want to add marker in fragment class with location from recycledview. Object with location data is in ClubBean. I obtained this by interface ClubAdapter.OnClubClickListener:
#Override
public void onClicked (ClubBean club) {
ClubBean bean = club;
Log.d("Name: ", bean.getClubName());
}
Main Activity:
public class MapsActivity extends FragmentActivity implements LoadAllClubsInterface, ClubAdapter.OnClubClickListener {
private DrawerLayout drawerLayout;
private RecyclerView clubRecycler;
private RecyclerView.LayoutManager clubLayoutManager;
private ArrayList<ClubBean> clubList = new ArrayList<ClubBean>();
private RecyclerView.Adapter clubAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new MyMapFragment()).commit();
new LoadAllClubs(this).execute(); //load list in background from database
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
clubRecycler = (RecyclerView) findViewById(R.id.recycler_view);
clubRecycler.setHasFixedSize(true);
clubLayoutManager = new LinearLayoutManager(this);
clubRecycler.setLayoutManager(clubLayoutManager);
}
#Override
public void finishDataLoad(ArrayList<HashMap<String, String>> clubs) {
Iterator<HashMap<String, String>> iterator = clubs.iterator();
Map<String, String> map = new HashMap<String, String>();
while (iterator.hasNext()){
map = iterator.next();
clubList.add(new ClubBean(map.get("name"),map.get("localization"), map.get("score")));
}
//pass the class that implements your listener as a parameter.
clubAdapter = new ClubAdapter(clubList, this, this);
clubRecycler.setAdapter(clubAdapter);
}
#Override
public void onClicked (ClubBean club) {
ClubBean bean = club;
Log.d("Name: ", bean.getClubName());
}
}
My MapFragment Class:
public class MyMapFragment extends Fragment implements OnMapReadyCallback{
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
public MyMapFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.map_fragment, container, false);
return mView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.map);
if (mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getActivity().getApplicationContext());
mGoogleMap = googleMap;
LatLng triCity = new LatLng(54.4158773,18.6337789);
mGoogleMap.addMarker(new MarkerOptions().position(triCity).title("Trojmiasto"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(triCity, 11));
}
}
The convenient way of communication between Activity and Fragment is via Interface. Here is example code based on your problem:
Step 1: Define an interface like this:
public interface IFragmentController{
void passDataToFragmentMethod(String someStringValue);
}
Step 2:Implement this Interface into your fragment. Then you will get passDataToFragmentMethod(String someStringValue) method in your fragment.
public class MyMapFragment extends Fragment implements IFragmentController{
#Override
void passDataToFragmentMethod(String someStringValue){
// So your logic code here using passed value
}
}
Step 3: In your Activity just get instance of your fragment and call passDataToFragmentMethod method in this way:
Fragment mapFragment=new MyMapFragment();
and
#Override
public void onClicked (ClubBean club) {
ClubBean bean = club;
Log.d("Name: ", bean.getClubName());
mapFragment.passDataToFragmentMethod(bean.getClubName());
}
Hope this will help you to solve your problem :)
The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.
https://developer.android.com/training/basics/fragments/communicating.html
Just define a method in MyMapFragment like addMarkers, then call it from activity.
You can do something like this
public class MapsActivity extends FragmentActivity implements LoadAllClubsInterface, ClubAdapter.OnClubClickListener {
MyMapFragment mMyFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMyFragment=new MyMapFragment();
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,mMyFragment).commit();
}
private void addMarkers(){
//defined this method in Mapfragment
mMyFragment.addMarkers();
}
if u have list then
For(ClubBean obj:ClubList)
{
// latitude and longitude
double latitude =obj.getLatValue();
double longitude = obj.getLngValue();
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps ");
// adding marker
googleMap.addMarker(marker);
}

Map in fragment Android result in error

i try to create a map in a fragment in a swipe view, but with this code i have a error in logcat, this is the code:
public class Mapa extends Fragment {
private static final double MARKER_LATITUDE = 42.027325;
private static final double MARKER_LONGITUDE = -8.640842;
GoogleMap map;
private FragmentActivity myContext;
public Mapa() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Mapa newInstance() {
Mapa fragment = new Mapa();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.mapa, container, false);
final LatLng position = new LatLng(MARKER_LATITUDE, MARKER_LONGITUDE);
// camera position
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener()
{
#Override
public void onCameraChange(CameraPosition arg0)
{
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(position, 17);
map.animateCamera(cu);
map.setOnCameraChangeListener(null);
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
return android;
}
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.mapFragment);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
}
and this is the logcat error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnCameraChangeListener(com.google.android.gms.maps.GoogleMap$OnCameraChangeListener)' on a null object reference
at greetrack.estg.ipvc.greentrack.Mapa.onCreateView(Mapa.java:49)
its my first application using maps, maybe somethings is wrong
You havent setup map, its null. So the null reference.
Map = ((MapFragment) getFragmentManager().findFragmentById(
R.id.mapView)).getMap();
is one way, or potentially following googles recommendation. Here is a maps fragment xml.
The xml file i put in isn't showing https://developers.google.com/maps/documentation/android/start#get_an_android_certificate_and_the_google_maps_api_key here is the linkk to it.
Add the following code in MainActivity.java.
package com.example.mapdemo;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Google maps for android - markers not showing

I'm creating a MapFragment in android; maps is showing just fine (although it takes 10 seconds to open), but no marker is shown.
This is the code of the fragment:
public class VehiclesMapFragment extends MapFragment implements OnMapReadyCallback {
GoogleMap _map;
private void setUpMapIfNeeded() {
if (_map == null) {
_map = this.getMap();
//_map = this.getMap();
//if (_map != null) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
ReDrawList(_vehicles);
}
}, 2000);
//}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
_map = googleMap;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
ReDrawList(_vehicles);
}
}, 10000);
}
public VehiclesMapFragment() {
}
VehiclesPosition[] _vehicles = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_vehicles = (VehiclesPosition[])getArguments().getSerializable("VEHICLES");
//setUpMapIfNeeded();
}
public void ReDrawList(VehiclesPosition[] vehicles)
{
if (vehicles != null && vehicles.length > 0 && _map != null) {
LatLngBounds bounds = null;
for (VehiclesPosition vp : vehicles) {
LatLng latlngPos = vp.GetMapLatLng();
if (bounds == null)
bounds = new LatLngBounds(latlngPos, latlngPos);
else
bounds = bounds.including(latlngPos);
MarkerOptions mi = vp.GetMapMarker();
Marker mm = _map.addMarker(mi);
mm.showInfoWindow();
}
try{
_map.animateCamera(CameraUpdateFactory.zoomTo(12));
_map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,100));
}catch (Exception exx) {
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_vehicles_map, container, false);
setUpMapIfNeeded();
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//setUpMapIfNeeded();
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onResume() {
super.onResume();
}
private OnFragmentInteractionListener mListener;
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
}
and this is the layout file:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
and the fragment is instantiated by an activity, with:
Bundle args = new Bundle();
args.putSerializable("VEHICLES",_VehiclesList);
fragment_units_map = new VehiclesMapFragment();
_fragment_units_map.setArguments(args);
calling _map.animateCamera produce an exception at every call:
java.lang.IllegalStateException: Error using newLatLngBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions.

android MapFragment doesn't show on replace

I have two FrameLayout in an activity, I just replace fragments inside those FrameLayout.
It works great with everyfragment BUT the one containing the MapFragment for the GoogleMap.
When I first launch the app it works and I see the map (everything works) but when I replace the fragment and replace it back I just get a blank space like nothing is loaded.
public class MapFragment extends CustomFragment {
private GoogleMap mMap;
private Marker currentMarker;
private OnFragmentInteractionListener mListener;
public static final String ID = "MAP_FRAGMENT";
private static View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
try {
view = inflater.inflate(R.layout.fragment_map, container, false);
} catch (InflateException e) {
Log.d("","");
}finally{
setUpMapIfNeeded();
if(view!=null)this.view=view;
return this.view;
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.map);
if (f != null)getActivity().getFragmentManager().beginTransaction().remove(f).commit();
mMap=null;
currentMarker=null;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((com.google.android.gms.maps.MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void update(FragmentMessage message) {
if(mMap!=null) {
Location loc = (Location) message.getMessages()[0];
if (currentMarker != null)
currentMarker.remove();
currentMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(loc.getLatitude(), loc.getLongitude())).title("Marker"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(loc.getLatitude(), loc.getLongitude())) // Sets the center of the map to Mountain View
.zoom(15) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
The mMap is never null, so the MapFragment is working I guess but I don't get anything on the screen (see screenshots below).
Does anyone have an idea ? I really don't know what is wrong.

Remove button overlays from SupportMapFragment

I have a very simple SupportMapFragment to display a small Google map which I use in this view
The idea is that the user can click it to view a full screen map.
How can I get rid of the +/- button from the map?
If it's not possible, is there an alternative method to get a map?
Here is my MapFragment code:
public class CustomMapFragment extends SupportMapFragment {
private static LatLng mPosFija;
public CustomMapFragment() {
super();
}
public static CustomMapFragment newInstance(LatLng position) {
CustomMapFragment fragment = new CustomMapFragment();
mPosFija = position;
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getMap() != null) {
initMap();
Log.d(getClass().getSimpleName(), "Map ready for use!");
}
}
#Override
public void onResume() {
super.onResume();
initMap();
}
private void initMap() {
Log.v("CustomMapFragment", "initMap");
if (getMap() != null) {
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(false);
getMap().clear();
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(mPosFija, 5));
getMap().addMarker(new MarkerOptions().position(mPosFija).draggable(false));
}
}
}
This is the code for my DialogFragment that adds the mapFragment to the view:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SERVICE_INVALID
|| GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SERVICE_MISSING) {
Log.e("HERE", "Google play not active");
TextViewFragment tvf = new TextViewFragment();
getChildFragmentManager().beginTransaction().replace(R.id.mapview, tvf).commit();
} else {
CustomMapFragment mMapFragment = CustomMapFragment.newInstance(new LatLng(offer.latitude, offer.longitude));
getChildFragmentManager().beginTransaction().replace(R.id.mapview, mMapFragment).commit();
}
}
Ok, so this was staring me in the face and was as simple as
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(false);
settings.setMyLocationButtonEnabled(false);
settings.setZoomControlsEnabled(false);

Categories

Resources