0

I have integrated Google Maps in ViewPager and afterward, when I close my app by pressing back button, I get "Unfortunately app has closed" message. If anyone have gone through issue and get solved, please let me know how to solve it.

Code

public class NearestBathroomMapView extends Fragment {

//Declare all necessary objects
public static View view;
public static GoogleMap gMap;
public static Double latitude,longitude;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    if(container==null){
        return null;
    }

    //Inflate the view  
    view= inflater.inflate(R.layout.bathroomsmapview,
            container, false);

    latitude=27.706750;//declare latitude and logitude
    longitude=85.314513;

    setUpIfMapNeeded();

    //call this function to obtain SupportMapFragment

    return view;
}

//Get the map from SupportMapFragment
public void setUpIfMapNeeded(){
    // Try to obtain the SupportMapFragment if map does not equal null. 
    if (gMap == null) {
        gMap = ((SupportMapFragment) BathroomInformation.fragmentManager
                .findFragmentById(R.id.location_map)).getMap();

        //call this function to display map  
        if (gMap != null){  
            setUpMap();
        }
    }
}

private void setUpMap() {
    gMap.setMyLocationEnabled(true);

    //add marker in map   
    gMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"))  

    //setup map position and animate it
    gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
            longitude), 12.0f));
}

public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    //view created to display map
    if (gMap != null)
        setUpMap();

    //get SupportMapFragment if map is equal to null
    if (gMap == null) {
    gMap = ((SupportMapFragment) BathroomInformation.fragmentManager
            .findFragmentById(R.id.location_map)).getMap();

    //set up map if map is not null    
    if (gMap != null)
        setUpMap();
    }
}

//should I need to call this below function onBackPressed method ??
public void onDestroyView() {
    super.onDestroyView();
    //map fragment get remove from FragmentManager          
    if (gMap != null) {
        BathroomInformation.fragmentManager.beginTransaction()
                .remove(BathroomInformation.fragmentManager
                        .findFragmentById(R.id.location_map)).commit();
        gMap = null;
    }
}

}
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
user2273146
  • 1,602
  • 2
  • 14
  • 27

1 Answers1

1

I think you should eliminate your

public void onDestroyView()

function. I don't see correct to remove a fragment that is destroyed.

Hope it helps.

Junior Buckeridge
  • 2,075
  • 2
  • 21
  • 27