我正在开发一个应用,其中onLongClick
将标记放到谷歌地图上。我的问题是在应用关闭时保存这些标记。
我使用了共享首选项来保存lat和lng的值,并在应用重新启动时加载这些值。但是,当我将这些值传递给方法来制作标记时,错误cat说我试图在空引用上调用方法。
非常感谢任何帮助。请在下面找到代码。
public class SecondMaps extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
EditText addressEditText;
String title;
LatLng position1;
SharedPreferences sharedPreferences;
int locationCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_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);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// If locations are already saved
if (locationCount != 0) {
String lat = "";
String lng = "";
// Iterating through all the locations stored
for (int i = 0; i < locationCount; i++) {
// Getting the latitude of the i-th location
lat = sharedPreferences.getString("lat" + i, "0");
// Getting the longitude of the i-th location
lng = sharedPreferences.getString("lng" + i, "0");
Toast.makeText(this, lat + "," + lng, Toast.LENGTH_LONG).show();
double lat3 = Double.valueOf(lat).doubleValue();
double lng3 = Double.valueOf(lng).doubleValue();
position1 = new LatLng(lat3, lng3);
drawMarker(position1);
}
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(this);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
// Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
public void homeClick(MenuItem item) {
startActivity(new Intent(this, Home.class));
}
public void mapClick(MenuItem item) {
startActivity(new Intent(this, SecondMaps.class));
}
public void settingsClick(MenuItem item) {
startActivity(new Intent(this, Settings.class));
}
@Override
public void onMapLongClick(LatLng latLng) {
addressEditText = (EditText) findViewById(R.id.editTextAddMarker);
title = addressEditText.getText().toString();
if (title.length() > 2) {
MarkerOptions markerOpt1 = new MarkerOptions()
.title(title)
.anchor(0.5f, 0.5f);
markerOpt1.position(latLng);
mMap.addMarker(markerOpt1);
Toast.makeText(this, "Reminder Added", Toast.LENGTH_LONG).show();
addressEditText.setText("");
locationCount++;
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat" + Integer.toString((locationCount - 1)), Double.toString(latLng.latitude));
// Storing the longitude for the i-th location
editor.putString("lng" + Integer.toString((locationCount - 1)), Double.toString(latLng.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Saving the values stored in the shared preferences */
editor.commit();
} else if (title.length() < 1) {
Toast.makeText(this, "Enter Reminder", Toast.LENGTH_LONG).show();
}
}
private void drawMarker(LatLng point){
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
mMap.addMarker(markerOptions);
}
public void clearMarker(View view) {
// Opening the editor object to delete data from sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clearing the editor
editor.clear();
// Committing the changes
editor.commit();
}
}
错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{conenterprize.remintherefv/conenterprize.remintherefv.SecondMaps}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
答案 0 :(得分:4)
请勿尝试与onCreate
或其他一些启动生命周期方法中的Google地图进行互动,因为地图在作为布局添加后不会立即就绪。
相反,请在onMapReady
方法中绘制标记。