NullPointerException When Trying to place Marker on Google Map V2

落花浮王杯 提交于 2020-01-24 19:32:06

问题


when I try to place Marker on google map with placeMarker method I get NullPointerException

NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference`
I/DpmTcmClient: RegisterTcmMonitor from: org.apache.http.impl.conn.TcmIdleTimerMonitor
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2
I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2
D/GoogleCertificates: com.google.android.gms.googlecertificates module is loaded
E/url: http://maps.googleapis.com/maps/api/geocode/json?latlng=35.7742618,51.3596331&sensor=true
E/Lat Long to Addresss:
E/Googlemap: null
D/GoogleCertificatesImpl: Fetched 363 Google certificates
I/b: Sending API token request.
E/b: Authentication failed on the server.
E/Google Maps Android API: Authorization failure
Ensure that the "Google Maps Android API v2" is enabled.
                                                                                 Ensure that the following Android Key exists:

Also I used getAsyncMap and OnMapReady().Inside OnMapReady I invoke an Asynktask to get user location and onPostExecute placeMarker Method is invoked:

public void placeMarker(LatLongDetails user_latlongobj2,
final Context contextPlace) {


try {
if (googlemap == null) {
    intialiseMap();
    animatecamera(user_latlongobj);
}
if (LoginDetails.Address.length() < 1) {
    LoginDetails.Address = "Getting your location .....";
}
googlemap.clear();
marker = new MarkerOptions().position(
        new LatLng(user_latlongobj2.user_latitude,
                user_latlongobj2.user_longitude)).title(
        LoginDetails.Address);

System.out.println("This is the Address" + LoginDetails.Address);

marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));


googlemap.addMarker(marker).showInfoWindow();
System.out.println("PLACING MARKER" + LoginDetails.Address);
if (marker == null || contextPlace == null) {
    Intent in =new Intent(this,ProfileActivity1.class);
    in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(in);
}
else
fixmarker(marker, contextPlace);

} catch (Exception e) {
fixmarker(marker, contextPlace);
Log.d("Profileactivity", "" + e);
  } 

}

All these problem came along when I tried to change getMap() to getAsyncMap() Also pls check This link And the complete Whole Activity on GitHub

I removed try and catch to find more details about error.here is logcat:

enter code herejava.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                            at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
                                                                            at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
                                                                            at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:551)
                                                                            at android.content.Context.getString(Context.java:413)
                                                                            at com.example.cabbookinghome.ProfileActivity1.intialiseMap(ProfileActivity1.java:280)
                                                                            at com.example.cabbookinghome.ProfileActivity1.placeMarker(ProfileActivity1.java:327)
                                                                            at epbit.helper.ConversionTaskLatLonLoc.onPostExecute(ConversionTaskLatLonLoc.java:130)
                                                                            at epbit.helper.ConversionTaskLatLonLoc.onPostExecute(ConversionTaskLatLonLoc.java:24)
                                                                            at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                            at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)

回答1:


After 3 Days Searching and Working on it here is what finally worked.the real problem is googlemap is null which means map is not loaded.I used try and catch but You should never just catch and exception and do nothing. after Log the exceptions, check the logs I found this:

com.google.android.gms.maps.MapFragment.getMap()' on a null object reference

First I tried This link Google Map returning nullpointerexception Google Maps Android V2

googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();

Then getChildFragmentManager become red indicating getChildFragmentManager () cannot be resolved or cannot be referenced.using getSupportFragmentManager() instead as described in this link (getChildFragmentManager () cannot be resolved or cannot be referenced) finally solved the problem and map has been loaded

googlemap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapfragment)).getMap();

Note that if your class extends from AppCompatActivitythen You need to use getSupportFragmentManager() because getChildFragmentManager() is a method of a Fragment not accessible fromAppCompatActivity




回答2:


This is because google map object is cleared after if statement . Remove googlemap.clear() and try.




回答3:


Your map doesn't initialize or not to get your position. Check location sensor is active or not. If not, please active it. You can try this code.

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 = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
        mMap.setMyLocationEnabled(true);


    }


来源:https://stackoverflow.com/questions/40607001/nullpointerexception-when-trying-to-place-marker-on-google-map-v2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!