NullPointerException试图将Marker放置在Google Map V2上时

时间:2016-11-15 10:05:04

标签: android google-maps nullpointerexception google-maps-android-api-2

当我尝试使用placeMarker方法将Marker放置在谷歌地图上时,我得到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:

我还使用了getAsyncMap和OnMapReady()。在OnMapReady中,我调用Asynktask获取用户位置,并调用onPostExecute placeMarker方法:

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);
  } 

}

当我尝试将getMap()更改为getAsyncMap()时,所有这些问题都出现了。请检查此link以及GitHub上的完整整个活动

我删除了try和catch以查找有关error的更多详细信息。这是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)

3 个答案:

答案 0 :(得分:2)

经过3天的搜索和处理,这里终于工作了。真正的问题是googlemap是null,这意味着地图没有加载。我使用了try和catch但是你应该永远不会捕获和异常而什么都不做。 记录异常后,检查我发现的日志:

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

首先,我尝试了此链接Google Map returning nullpointerexception Google Maps Android V2

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

然后getChildFragmentManager变为红色,表示无法解析getChildFragmentManager()或无法引用。使用getSupportFragmentManager(),而不是如此链接中所述 (getChildFragmentManager () cannot be resolved or cannot be referenced)终于解决了问题并且已经加载了地图

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

请注意,如果您的班级来自AppCompatActivity,那么您需要使用getSupportFragmentManager()  因为getChildFragmentManager()是无法从AppCompatActivity

访问的片段方法

答案 1 :(得分:0)

这是因为在if语句之后清除了谷歌地图对象。删除googlemap.clear()并尝试。

答案 2 :(得分:0)

您的地图未初始化或未获得您的位置。检查位置传感器是否有效。如果没有,请激活它。你可以尝试这段代码。

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);


    }