I am not able to figure out why i am getting null pointer exception everytime i am running the app.This android app finds the place and marks it on the map using geocoding.But i have not succeded in doing so and not getting to know where is the mistake.Please help!
The main activity code is as follows:
package com.dutt.rishabh.locator;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
EditText x;
Button bfind;
String location;
MarkerOptions markerOptions;
#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);
bfind=(Button)findViewById(R.id.bfind);
View.OnClickListener findClickListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
x=(EditText)findViewById(R.id.etsearch);
location=x.getText().toString();
if(location!=null || location.equals("")){
new GeocoderTask().execute(location);
}
}
};
bfind.setOnClickListener(findClickListener);
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... strings) {
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses=null;
try {
addresses=geocoder.getFromLocationName(strings[0],3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses){
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(),"No location found",Toast.LENGTH_SHORT).show();
}
mMap.clear();
for(int i=0;i<addresses.size();i++){
Address address= addresses.get(i);
LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
String addressText=String.format("%s,%s",address.getMaxAddressLineIndex()>0?address.getAddressLine(0):"",address.getCountryName());
markerOptions=new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
mMap.addMarker(markerOptions);
if(i==0){
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Please help and kindly mention my mistake so i can understand.
The following is the logcat :
07-26 15:02:02.264 30388-30388/com.dutt.rishabh.locator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dutt.rishabh.locator, PID: 30388
java.lang.NullPointerException
at com.dutt.rishabh.locator.MapsActivity$GeocoderTask.onPostExecute(MapsActivity.java:75)
at com.dutt.rishabh.locator.MapsActivity$GeocoderTask.onPostExecute(MapsActivity.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Null check for addresses
for(int i=0;i<addresses.size();i++){
}
or add return
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(),"No location found",Toast.LENGTH_SHORT).show();
return;
}
In your case the address list seems to be null. You can return code execution after showing the toast message.
if(addresses==null || addresses.size()==0){ // Line 71
Toast.makeText(getBaseContext(),"No location found",Toast.LENGTH_SHORT).show();
return;
}
Related
My problem is: When I'm trying to move around in the map or zoom in & out it immediately return to my current location. Also when I search for location, new marker added at the searched location but immediately goes back to my current location.
I searched for solution but found nothing.. I hope somebody can figure it out
package com.hitman.locationrevision;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationRequest;
import android.os.Bundle;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hitman.locationrevision.databinding.ActivityMapsBinding;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
LocationManager locationManager;
LocationListener locationListener;
>function for current location information
public void locationInfo(Location location,String title){
if(location != null) {
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(currentLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
}
}
>function to request permission from user
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationInfo(lastLocation,"Your lastLocation");
}
}
}
private GoogleMap mMap;
private ActivityMapsBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Intent intent=getIntent();
locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener=new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
locationInfo(location,"Your Location");
}
};
>code to ask permission and check permission from user
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
>code to find the last location and update the last location
Location
lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationInfo(lastLocation,"Your lastlocation");
}
}
}
Its because you have move camera when your location update. You just need to put condition whether its user call or not to see current location.
Here is the line, this will alway move camera and display your current location
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
You can do like this, whenever user required to see current location then change fromUser = true and then make to false back. Just like happen in Google Map when you click on location button.
var fromUser = false;
if(fromUser){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
fromUser = false;
}
Use this code for get current location.this method only get one time
of user location.inside OnLocationResult callback handle your location
logic
private void getCurrentLocation(){
LocationRequest locationRequest = new LocationRequest();
FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setMaxWaitTime(1000);
locationRequest.setFastestInterval(500);
locationRequest.setInterval(500);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback() {
#Override
public void onLocationResult( LocationResult locationResult) {
if(locationResult.getLocations().size() != 0){
Location location = locationResult.getLocations().get(0);
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
//handle current user location logic
FusedLocationProviderClient.removeLocationUpdates(this);
}
}
}, Looper.getMainLooper());
}
This question already has answers here:
Android LocationListener, AbstractMethodError on onStatusChanged and onProviderDisabled
(6 answers)
Closed 1 year ago.
I've tried this code from an UDEMY Course. Written same like him, he can access to location & also got a Toast while I cant opening app with allowed Location.
When allowing location, my app crashing.
But when deny I can see the map and not crashing anymore.
***My google map API also working good. also taken user Internet & Location Service.
MapsActivity.java:
package com.project.demo2map;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.project.demo2map.databinding.ActivityMapsBinding;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private ActivityMapsBinding binding;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, locationListener);
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
Toast.makeText(MapsActivity.this, location.toString(), Toast.LENGTH_SHORT).show();
}
};
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.
GPS_PROVIDER, 0, 0, locationListener);
}else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.
GPS_PROVIDER, 0, 0, locationListener);
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
CrashLog:
2021-10-25 14:59:29.003 25984-25984/com.project.demo2map D/AndroidRuntime: Shutting down VM
2021-10-25 14:59:29.006 25984-25984/com.project.demo2map E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.project.demo2map, PID: 25984
java.lang.AbstractMethodError: abstract method "void android.location.LocationListener.onProviderDisabled(java.lang.String)"
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:365)
at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:275)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:291)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)
Overriding the onProviderChanged() method will fix this problem.
check if any providers active.
if( locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ||
locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER)){
//start listener to requestUpdates ...
}else{
//show message, no providers enabled.
}
I encountered error inflating class fragment when I tried to mark the location (lat and longitude from SQL) onto the google map for the android java app. In MapsActivity.java, it is already using onCreate, not onCreateView. Do I have to change it or is there any way I can solve the error?
MapsActivity.java
package com.example.paddy_disease_tracker;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.example.paddy_disease_tracker.databinding.ActivityMapsBinding;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
String query;
Statement st;
ResultSet rs;
Toast toast;
String disease;
float lat,lon;
private GoogleMap mMap;
private ActivityMapsBinding binding;
LatLng centerLocation,place;
Connection connect;
ArrayList<LatLng> places=new ArrayList<LatLng>();
ArrayList<String> dis=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 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);
centerLocation=new LatLng(6.0,101);
try {
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connectionclass();
if (connect != null) {
query = "Select * from Disease";
st = connect.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
disease=rs.getString(3);
lat=rs.getFloat(4);
lon=rs.getFloat(5);
places.add(new LatLng(lat,lon));
dis.add(disease);
}
} else {
toast=Toast.makeText(getApplicationContext(),"Check Connection",Toast.LENGTH_LONG);
toast.show();
}
}catch(Exception e){
toast=Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG);
toast.show();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
enableMyLocation();
// Add a marker in Sydney and move the camera
for(int i=0; i<places.size();i++){
mMap.addMarker(new MarkerOptions().position(places.get(i)).title(dis.get(i)+" found"));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(centerLocation,6));
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
} else {
String []perms={"android.permission.ACCESS_FINE_LOCATION"};
// Permission to access the location is missing. Show rationale and request permission
ActivityCompat.requestPermissions(this,perms,200);
}
}
}
I am a new learner in Java. As the title describes, I can't roam freely on google maps in the emulator PIXEL 2 API 29. The camera is stuck in the center of the location and no matter what I can't get the camera to elsewhere. I dont think it is the API cuz I have tested it without the code. Open to the suggestions, thank you. here is the code;
`
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,15));
System.out.println("location: " + location);
}
};
if(Build.VERSION.SDK_INT >= 23) {
if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION},1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0,locationListener);
}
}else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0,locationListener);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length> 0){
if(requestCode==1){
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0,locationListener);
}
}
}
}
}`
This is because the function onLocationChanged() of LocationLister in your code moves the camera to the current location of your device that gets triggered whenever the center of the map is not in the current location of the device.
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,15));
System.out.println("location: " + location);
}
LocationListener location is registered through the location manager service using the locationManager.requestLocationUpdates(). To learn more please see the documentation here.
If your main goal is to get the current device location and display it on the map as it loads, there is an official documentation from Google Maps Platform to guide you on how to do it. To get you started, you can check it here.
The following code is from a Google maps activity to find a particular location on user input.It works fine but crashes when there is no persistent internet connection.Please help me fix this problem.
The MainActivity.java class looks like this:
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MainActivity
extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Getting reference to btn_find of the layout activity_main
Button btn_find = (Button) findViewById(R.id.btn_find);
// Defining button click event listener for the find button
OnClickListener findClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText etLocation = (EditText) findViewById(R.id.et_location);
// Getting user input location
String location = etLocation.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
};
// Setting button click event listener for the find button
btn_find.setOnClickListener(findClickListener);
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask
extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0) {
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
}
And this is my crash report:
02-25 17:17:42.157 4312-4312/aravindaby.myapp123 E/test: Exception
02-25 17:17:42.157 4312-4312/aravindaby.myapp123 E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at aravindaby.myapp123.MainActivity$GeocoderTask.onPostExecute(MainActivity.java:100)
at aravindaby.myapp123.MainActivity$GeocoderTask.onPostExecute(MainActivity.java:72)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4793)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
at dalvik.system.NativeStart.main(Native Method)
In the case of no internet connection, address is null. So after showing Toast message, you should return the control.
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
return;
}