android:Location返回null对象引用错误

时间:2016-10-06 22:21:07

标签: android location

我正在尝试获取用户的位置,更具体地说是他们的城市。该应用程序在运行时请求权限。但是当它试图将位置放入ArrayList时,它会给出一个空对象引用错误。

我将评论下面的具体行。

我做错了什么?

错误

尝试调用虚方法' java.util.List android.location.Geocoder.getFromLocation(double,double,int)'在空对象引用上

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) {

    }
}

1 个答案:

答案 0 :(得分:1)

您似乎尚未初始化myGeo引用。

要修复它,只需在调用getFromLocation()之前初始化它。作为旁注,您还应确保Location不为null,因为locationManager.getLastKnownLocation()调用可能会返回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);

    }
}