我試圖將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) –