Reputation: 286
I am trying set a custom marker in GMaps for which i have created a custom layout. I am inflating my custom layout in my Maps Activity then converting it into Bitmap and then passing the same bitmap to BitmapDescriptorFactory.fromBitmap(bitmap)
but i am getting java.lang.NullPointerException: null reference
Here is my Map Activity
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) {
}
});
}
}
My Custom Marker Layout which i am inflating in My Java file (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>
My Error Log:
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: I am using Android Networking Library for Network Operations.
Upvotes: 1
Views: 477
Reputation: 286
I used the Bitmap Conversion method from this tutorial and it worked. May be i was doing something wrong in the converting the layout into bitmap.. thanks all for your help..
Upvotes: 0
Reputation: 61
I guess Null Pointer Exception
is due to map not being ready yet when you call drawMarker
method inside getCurrentLocation()
method.
Try calling getCurrentLocation()
method from onMapReady
method when the map is ready to be used and remove getCurrentLocation()
method call inside onCreate
method.
Upvotes: 1