Ahmad Ahmad - 1 month ago 18
Android Question

Map Return NULL

When Application run always return NULL Exception

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference


if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {

@Override
public void onMapReady(GoogleMap googlemap) {
// TODO Auto-generated method stub
map=googlemap;
// startMap();
}
});
}


Xml Code is here where i used Map *

<fragment
android:id="@+id/map"
class="com.shahi.driver.locationfiles.TouchableMapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

Answer Source

Your class will be:

public class YourActivity extends Activity implements OnMapReadyCallback {

    @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.your_layout);
            try {
                // Loading map
               MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
                mapFragment.getMapAsync(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    @Override
        protected void onResume() {
            super.onResume();
            MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
                mapFragment.getMapAsync(this);
        }

    @Override
        public void onMapReady(final GoogleMap googleMap) {
            final LatLng current_position = new LatLng(your_latitude, your_longitude);
            MarkerOptions marker = new MarkerOptions().position(current_position).title("Your Address").snippet("Anything");
            googleMap.addMarker(marker);
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(current_position, 12));
            googleMap.getUiSettings().setMapToolbarEnabled(true);
            googleMap.setMyLocationEnabled(true);
        }
    }

and your_layout.xml will be:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.MapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</LinearLayout>