我试图将OnMapLongClickListener
应用到我的地图应用程序,以便每当用户长时间点击屏幕时,相应位置就会出现一个标记。为什么onMapLongClick引发RuntimeException?
我的MainActivity类别如下:
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap.setOnMapLongClickListener(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Hatfield and move the camera
LatLng hatfield = new LatLng(51.7471060, -0.22978);
mMap.addMarker(new MarkerOptions()
.position(hatfield)
.title("Hertfordshire Times")
.snippet("Hertfordshire Lecturer wins Nobel Prize")
.draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(hatfield));
mMap.addCircle(new CircleOptions()
.center(hatfield)
.fillColor(0x5500ff00)
.strokeColor(Color.WHITE).radius(60));
}
@Override
public void onMapLongClick(final LatLng latLng) {
if(mMap != null) {
Toast.makeText(this, "Long press", Toast.LENGTH_LONG).show();
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("You placed a marker here")
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
}
一旦OnMapLongClick
方法运行时,它抛出一个NullPointerException
(一个错误的片段如下所示):
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnMapLongClickListener(com.google.android.gms.maps.GoogleMap$OnMapLongClickListener)' on a null object reference
at com.example.paulmbw.map_application_fyp.MapsActivity.onCreate(MapsActivity.java:29)
任何想法,我做错了吗?我在堆栈上看到了类似的答案,但似乎无法找到解决我的问题的方法。任何帮助将不胜感激。
谢谢。
因为'mMap'是** ** NULL – Rami
将'mMap.setOnMapLongClickListener(this);'移动到'onMapReady()'方法。 –
可能的重复[什么是空指针异常,以及如何解决它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) –