尝试在GMaps中设置自定义标记时出现空指针异常

时间:2016-12-25 14:26:53

标签: android google-maps nullpointerexception google-maps-markers bitmapfactory

我正在尝试在GMaps中设置自定义标记,我为其创建了自定义布局。我在我的地图活动中对我的自定义布局进行了膨胀,然后将其转换为位图,然后将相同的位图传递给BitmapDescriptorFactory.fromBitmap(bitmap),但我得到java.lang.NullPointerException: null reference这是我的地图活动

public class GPSLocation extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback {
    LatLng latLng = null;
    GoogleApiClient googleApiClient;
    GoogleMap map;
    int animation = 0;
    TextView marker;
    View v;
    Bitmap mainBitmap;
    LayoutInflater inflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflater = getLayoutInflater();
        setContentView(R.layout.activity_gpslocation);
        v = inflater.inflate(R.layout.marker,null);
        marker = (TextView) v.findViewById(R.id.marker);
        mainBitmap = ConvertToBitmap(v);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        checkGps();
        getCurrentLocation();

    }

    protected Bitmap ConvertToBitmap(View v) {
        Bitmap map2;
       Log.v("BitmapObject", "Inside");
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        return map2 = v.getDrawingCache();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;
    }

    //Gets Current Location
    private LatLng getCurrentLocation() {
        new SamLocationRequestService(GPSLocation.this).executeService(new SamLocationRequestService.SamLocationListener() {
            @Override
            public void onLocationUpdate(Location location, Address address) {
                latLng = new LatLng(location.getLatitude(), location.getLongitude());

                drawMarker(latLng, mainBitmap, "My Location");
                getPlaces(location.getLatitude() + "", location.getLongitude() + "", "500", "atm");
                Toast.makeText(GPSLocation.this, location.getLatitude() + "," + location.getLongitude() + "", Toast.LENGTH_SHORT).show();
            }
        });


        return latLng;
    }

    //Check GPS is turned On or not
    private void checkGps() {
        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(GPSLocation.this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            googleApiClient.connect();

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
            builder.setAlwaysShow(true);
            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    final LocationSettingsStates state = result.getLocationSettingsStates();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            getCurrentLocation();
                            googleApiClient = null;
                            // All location settings are satisfied. The client can initialize location
                            // requests here.
                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the user
                            // a dialog.
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(GPSLocation.this, 1000);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            googleApiClient = null;
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // Location settings are not satisfied. However, we have no way to fix the
                            // settings so we won't show the dialog.
                            googleApiClient = null;
                            break;
                    }
                }
            });
        }
    }
    //End

    public void drawMarker(LatLng latLng, Bitmap bitmap, String name) {


        if (animation == 0) {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLng)             // Sets the center of the map to location user
                    .zoom(15)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            animation = 1;
        }

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title(name);
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap));
        map.addMarker(markerOptions);
    }


    void getPlaces(String lat, String lon, String radious, String type) {
        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location=" + lat + "," + lon);
        sb.append("&radius=" + radious);
        sb.append("&types=" + type);
        sb.append("&sensor=true");
        sb.append("&key=MyAPIKey");
        AndroidNetworking.initialize(GPSLocation.this);
        AndroidNetworking.get(sb.toString())
                //.addJSONObjectBody(object)
                .setTag("Token")
                .setPriority(Priority.MEDIUM)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray array = response.getJSONArray("results");
                            for (int i = 0; i < array.length(); i++) {

                                JSONObject object = array.getJSONObject(i);
                                String latitude = object.getJSONObject("geometry").getJSONObject("location").getString("lat");
                                String longitude = object.getJSONObject("geometry").getJSONObject("location").getString("lng");
                                String name = object.getString("name");
                                String vicinity = object.getString("vicinity");
                                String reference = object.getString("reference");
                                LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                                marker.setText(name.toString());
                                //drawMarker(latLng, mainBitmap, name + "\n" + vicinity);
                            }
                            //drawMarker(CurrentPos, "My Location", "0", BitmapDescriptorFactory.HUE_BLUE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });
    }

}

我在自己的Java文件(marker.xml)中膨胀的自定义标记布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/google_selector"
        android:gravity="center"
        android:padding="2dp"
        android:text="ATM"
        android:textColor="#FFFFFF"
        android:textSize="9dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/marker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="4dp"
        android:text="Axis"
        android:textColor="#000000"
        android:textSize="9dp" />
</LinearLayout>

我的错误日志:

12-25 19:22:27.330 32741-32741/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.aamir.myapplication, PID: 32741
                                                   java.lang.NullPointerException: null reference
                                                       at maps.w.d.a(Unknown Source)
                                                       at maps.ad.f$a.<init>(Unknown Source)
                                                       at maps.ad.f.a(Unknown Source)
                                                       at maps.ad.S.<init>(Unknown Source)
                                                       at maps.ad.t.a(Unknown Source)
                                                       at xj.onTransact(:com.google.android.gms.DynamiteModulesB:167)
                                                       at android.os.Binder.transact(Binder.java:392)
                                                       at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addMarker(Unknown Source)
                                                       at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
                                                       at com.example.aamir.myapplication.GPSLocation.drawMarker(GPSLocation.java:190)
                                                       at com.example.aamir.myapplication.GPSLocation$1.onLocationUpdate(GPSLocation.java:109)
                                                       at com.entire.sammalik.samlocationandgeocoding.SamLocationRequestService.onLocationChanged(SamLocationRequestService.java:101)
                                                       at com.google.android.gms.location.internal.zzk$zzb.handleMessage(Unknown Source)
                                                       at android.os.Handler.dispatchMessage(Handler.java:111)
                                                       at android.os.Looper.loop(Looper.java:207)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5776)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

P.S:我正在使用Android网络库进行网络操作。

2 个答案:

答案 0 :(得分:1)

我猜Null Pointer Exception是因为当您在drawMarker方法中调用getCurrentLocation()方法时地图尚未准备就绪。

在准备好使用地图时尝试从getCurrentLocation()方法调用onMapReady方法,并在getCurrentLocation()方法中删除onCreate方法调用。

答案 1 :(得分:0)

我使用了this教程中的位图转换方法,但它确实有效。可能是我在将布局转换为位图时做错了...感谢所有人的帮助..