我正在用Google地图制作搜索栏。 如果我尝试在某处搜索,该应用将关闭 这是我得到的错误
Caused by: 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
at com.example.yoons.honey.RealMap.onMapSearch(RealMap.java:71)
map.java
public class RealMap extends AppCompatActivity implements OnMapReadyCallback {
private Button searchButton;
GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.real_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
searchButton = new Button(this);
searchButton.setOnClickListener(search);
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private View.OnClickListener search=new View.OnClickListener(){
public void onClick(View v){
onMapSearch(v);
}
};
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() != 0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
} else {
Toast.makeText(getApplicationContext(), "location not found", Toast.LENGTH_SHORT).show();
}
}
}
}
我不知道我的代码为什么不起作用 我在互联网上复制了大部分代码 这是我认为最常见的搜索条形码,但对我不起作用
答案 0 :(得分:1)
将googleMap引用传递给您的变量mMap为:-
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}