I'm making a search bar with google maps. If I try to search somewhere the app will shutdown And this is the error I get
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();
}
}
}
}
I don't know why my code won't work I copied most of the code on the internet It's the most common search bar code I think but it doesn't work for me