I'm trying to show a GoogleMap in my App but I get problems right at the beginning of this task.
The line:
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
always returns null.
I have tried a lot of things but nothing works. Could you please help me to find the Problem?
Here is my Code:
public class MapSectionFragment extends Fragment implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
OnMyLocationButtonClickListener,
OnMapReadyCallback{
private GoogleMap map;
Location location;
GoogleApiClient mGoogleApiClient;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
private void createMapView(){
try{
//here it comes
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
map = mapFrag.getMap(); //throws NullPointerException
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_map,
container, false);
createMapView();
return rootView;
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
#Override
public void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
REQUEST,
this); // LocationListener
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
map.setMyLocationEnabled(true);
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(getActivity(), "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}
And here is the XML "fragment_section_map" with the mapID:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/refresh_map_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/refresh_map" />
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Thanks for your help!
please try this replace
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
With
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
because
getChildFragmentManager()
will managing fragments inside an fragment because your are using SupportMapFragment inside a fragment, so please try this solution
Hope this will help you
Related
I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
The map displays on the screen, i would attach an image but i require 10 points before I am able to. I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
I would attach an image of the displaying and interatable map here but I do not have 10 points.
https://i.imgur.com/mpp9aAY.png
It appears that you are focusing your map on the NY City area, but are pinning your marker in the middle of Nigeria. Are you sure that the marker is not successfully added? Try setting your marker near where you position the map focus.
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
these codes are necessary, else you won't get any callback to
onMapReady(GoogleMap googleMap) {}
I think the crash occurs because the variable gmap is not initialised. Just add gmap = map before adding the marker in the onMapReady.
in the following code does not display the marker.This code I have made with previews android studio editions and there was no problem with tracking but now there is.I want to make a google map with tracking tab and for this reason I think can't use activity but only fragment.Anyone knows how it can be done?
public class Tab2Map extends Fragment implements OnMapReadyCallback {
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
public Tab2Map() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_tab2, 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(getContext());
mGoogleMap = googleMap;
if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGoogleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());
mGoogleMap.addMarker(new MarkerOptions().position(latlng).title("Current Location").snippet(latlng.toString()));
CameraPosition position=CameraPosition.builder().target(latlng).zoom(16).bearing(0).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(position));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 15, locationListener);
}
}
fragment_tab2.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Tab2Map">
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"/>
</android.support.constraint.ConstraintLayout>
I am trying to create one flipview which is contain one side Google Map and one side Recyclerview.
I am getting an error while i try i call an Map fragment. it give nullpointer while map has to load at initialization time.
File 1 : fragment_left.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/transparent">
<fragment
android:id="#+id/map_fragment"
android:layout_below="#+id/header"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_above="#+id/footer"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
File 2 : fragment_right.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header"
android:background="#mipmap/back"
android:layout_above="#+id/footer"/>
</LinearLayout>
File 3 : flipscreen.xml
<RelativeLayout 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"
tools:context=".flipscreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#mipmap/gradiant"
android:layout_alignParentTop="true"
android:padding="6dp">
<TextView
android:id="#+id/activity_registration_txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold"
android:text="#string/events"/>
<ImageView
android:id="#+id/listOfEvent"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#mipmap/menu"/>
</RelativeLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_below="#+id/header"
android:layout_above="#+id/footer"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
</FrameLayout>
</RelativeLayout>
Java Files
File 1 : flipscreen.java :
public class flipscreen extends FragmentActivity {
private boolean showingBack;
private FragmentLeft left = new FragmentLeft();
private FragmentRight right = new FragmentRight();
private Context context;
private Handler handler;
private FlipAnimation flipAnimation;
private FlipAnimation backFlip;
private GoogleMap map;
private FragmentManager mFragmrg;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
FrameLayout mapLayout;
ImageView flipView;
ImageButton btnAddEvent;
String strUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flipscreen);
context = this;
handler = new Handler(getMainLooper());
mapLayout = (FrameLayout)findViewById(R.id.fragment_container);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, right, "fragmentRight").commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, left, "fragmentLeft").commit();
flipView=(ImageView) findViewById(R.id.listOfEvent);
btnAddEvent=(ImageButton)findViewById(R.id.btnAddEvent);
btnAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(strUserId.equals(""))){
startActivity(new Intent(flipscreen.this,AddEventActivity.class));
// finish();
}else{
startActivity(new Intent(flipscreen.this,LoginActivity.class));
}
}
});
flipView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipAnimation = new FlipAnimation(left.getView(), right.getView());
backFlip = new FlipAnimation(left.getView(), right.getView());
handler.removeCallbacks(rotate);
handler.postDelayed(rotate, 100);
}
});
}
private Runnable rotate = new Runnable() {
#Override
public void run() {
if (!showingBack) {
left.getView().startAnimation(flipAnimation);
right.getView().startAnimation(flipAnimation);
// Toast.makeText(context, "flip", Toast.LENGTH_LONG).show();
flipView.setImageResource(R.mipmap.nav_map);
showingBack = true;
} else {
showingBack = false;
backFlip.reverse();
// Toast.makeText(context, "backflip", Toast.LENGTH_LONG).show();
left.getView().startAnimation(backFlip);
right.getView().startAnimation(backFlip);
flipView.setImageResource(R.mipmap.menu);
}
}
};
}
File 2 : fragmentLeft.java :
public class FragmentLeft extends Fragment {
private GoogleMap map;
private FragmentManager mFragmrg;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
private SupportMapFragment mMapFragment;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View flipMap =inflater.inflate(R.layout.fragment_left, container,false);
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
// // Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(latitude, longitude);
map.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 8);
map.animateCamera(cameraUpdate);
System.out.println("Latitude "+latitude+ " \n Longitude "+longitude);
}
});
return flipMap;
}
}
File 3 : FragmentRight.java :
public class FragmentRight extends Fragment {
private static final String TAG ="NearByActivityList" ;
RecyclerView recyclerView;
List<Event> lsEvent=new ArrayList<Event>();
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
ImageView listOfEvent;
double latitude = 0;
double longitude = 0;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View fillData =inflater.inflate(R.layout.fragment_right, container,false);
recyclerView = (RecyclerView) fillData.findViewById(R.id.list);
GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (3 - position % 3);
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return fillData;
}
}
My issue is in fragmentLeft.java it's getting null
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
I have review your code and I think the error is R.id.map, you have not, #+id/map in xml you have #+id/map_fragment:
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map_fragment)
mapFragment.getMapAsync(new OnMapReadyCallback() {
I found this solution of my problem.. Here is the ans of that.
I found it in https://code.google.com/p/gmaps-api-issues/issues/detail?id=5064 Link.
FragmentLeft.java :
public class FragmentLeft extends Fragment {
private GoogleMap map;
GPSTracker gps;
private SupportMapFragment fragment;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View flipMap =inflater.inflate(R.layout.fragment_left, container,false);
gps = new GPSTracker(getActivity());
latitude = gps.getLatitude();
longitude = gps.getLongitude();
return flipMap;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map_fragment);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_fragment, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (map == null) {
map = fragment.getMap();
System.out.println("Latitude : = "+latitude+" Longitude : ="+longitude);
map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
LatLng sydney = new LatLng(latitude, longitude);
map.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12);
map.animateCamera(cameraUpdate);
}
}
}
i want to make maps in android fragment with use extend fragment
this is my code : Maps do not come up, and system force close
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.gmaps, container, false);
SupportMapFragment mapFragment = ((SupportMapFragment) getActivity().getSupportFragmentManager() .findFragmentById(R.id.map));
mapFragment.getMapAsync((OnMapReadyCallback) this.getActivity());
btnFindPath = (Button) view.findViewById(R.id.btnFindPath);
etOrigin = (EditText) view.findViewById(R.id.etOrigin);
etDestination = (EditText) view.findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
return view;
please help me, and thank you
You can try the below code :
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("onActivityCreated", "onActivityCreated");
if(supportMapFragment==null){
supportMapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
loadMapAtPosition(googleMap, CAMERA_INITIAL_LATITUDE, CAMERA_INITIAL_LONGITUDE);
}
});
}
.....
private void loadMapAtPosition(GoogleMap googleMap, double latitude, double longitude){ googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 6.0f)); }
Just Simple if you want to use Map in Fragment.
Try this
in you Fragment class.
GoogleMap map = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
and in your xml.
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
if you use google map within fragment then you should be use map
object like this.you have to use getChildFragmentManager() to find
fragment
<fragment
android:id="#+id/main_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" >
</fragment>
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.main_map);
I am using google maps v2 with actionbar tab fragment. everything is works fine but i need to update my maps location by passing lat long from first tab (first fragment) as map is on second tab. I am passing latlong via constructor.
firstly the problem was handling the lifecycle of fragment on viewpager, but by following this tutorial the problem was solved. now i am using map updation method in "onFragmentPause" but it is throwing null point exception still it works fine if i place it in "onViewCreate()" code showing in details.
Tracking fragment:
public class Track extends Fragment implements FragmentLifecycle {
private static GoogleMap mMap;
private static Double latitude, longitude;
private static String vAddress;
private static View Track;
DataHandler dh;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(activity instanceof DataHandler)
{
dh = (DataHandler)activity;
}
else
throw new ClassCastException();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Track = inflater.inflate(R.layout.activity_track, container, false);
return Track;
}
public void setUpMapIfNeeded() {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.location_map)).getMap();
setUpMap();
}
private static void setUpMap() {
try{
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(vAddress).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker2)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 12.0f));
}
catch(Exception e){
Log.wtf("this error", "ok");
}
}
public void onDestroyView() {
super.onDestroyView();
try {
Fragment fragment = (getFragmentManager().findFragmentById(R.id.location_map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPauseFragment() {
}
#Override
public void onResumeFragment() {
Log.i("state", "onResumeFragment()");
latitude= 73.023333; //getting latitude from first tab(fragment)by calling constructor
longitude= 67.939322;
vAddress = "some address";
setUpMapIfNeeded();
}
now if i place setUpMapIfNeeded() in onCreateView and change the rotation, it recreate and update the location but error when put in onResumeFragment().
kindly help me out and sorry if i could not describe effectively.
Error
since logcat shows the error at line 48. that is
.findFragmentById(R.id.location_map)).getMap();
this is Activity_Track
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/location_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
If i change from static values to this it crashes a give null point exception at line latitude= dh.getLat();
#Override
public void onResumeFragment() {
Log.i("state", "onResumeFragment()");
latitude= dh.getLat(); //getting latitude from first tab(fragment)by calling constructor
longitude= dh.getLong();
vAddress = dh.getAddress();
setUpMap();
}