SinTek Solutions SinTek Solutions - 2 months ago 24
Android Question

android: Location returns null object reference error

I am trying to get the user's location, more specifically their city. The app asks for permission at runtime. But when it tries to put the location into an ArrayList, it gives a null object reference error.

I will comment the specific line below.

What am I doing wrong?

ERROR

Attempt to invoke virtual method 'java.util.List android.location.Geocoder.getFromLocation(double, double, int)' on a null object reference

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class PhoneList extends AppCompatActivity implements LocationListener {


LocationManager locationManager;
private String provider;
public final static int MY_PERMISSIONS_REQUEST_READ_LOCATION = 1;
public double myLng;
public double myLat;
List addresses = new ArrayList();

public Geocoder myGeo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);

if (1 == 0) {
showAlert();
} else {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
GetLocationPermission();

return;
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);

myLat = location.getLatitude();
myLng = location.getLongitude();
}

}

private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}

public void GetLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_READ_LOCATION);
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
System.out.println("Yes");
} else {

System.out.println("boo");
}
return;
}
}
}

@Override
public void onLocationChanged(Location location) {
try {

//ERROR IS ON THIS LINE
addresses = myGeo.getFromLocation(location.getLatitude(), location.getLongitude(), 10);

} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);

}
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

Answer

Looks like you haven't initialized your myGeo reference.

To fix it, just initialize it before you call getFromLocation(). As a side note, you should also make sure that the Location is not null, since the locationManager.getLastKnownLocation() call has the potential to return null.

@Override
public void onLocationChanged(Location location) {
    try {
        //Add initialization:
        myGeo = new Geocoder(this, Locale.getDefault());
        //Make sure that the Location is not null:
        if (location != null) {
            addresses = myGeo.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
        }

    } catch (IOException e) {
        Log.e("LocateMe", "Could not get Geocoder data", e);

    }
}