Android Geocoder无法在API 23上运行

时间:2016-07-27 09:17:21

标签: android google-geocoder gmsplacepicker

我开发的应用程序在运行时使用lat和城市名称使用GPSTracker.java类并将此城市名称添加到url以获取retrive json数据。 从API 18到API 22我的代码工作得非常好但是现在当我在API 23上运行我的代码时,地理编码器不起作用,城市名称为null 这是我在重复城市名称的主要活动上的代码:

// To get City-Name from coordinates
    GPSTracker gpsTracker = new GPSTracker(getActivity());






    String cityName = null;
    Geocoder gcd = new Geocoder(getContext(), Locale.ENGLISH);
    List<Address> addresses = null;
    try {
        addresses = gcd.getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
        if (addresses.size() > 0) {
            System.out.println(addresses.get(0).getLocality());
            cityName = addresses.get(0).getLocality();
            Log.d("nome_cit", "debug_cit " + cityName);
            // Controllo formattazione nomi Car2Go
            if(cityName.equals("Rome")) {
                nome_citta = "Roma";
            }else if (cityName.equals("Florence")){
                nome_citta = "Firenze";
            }
            else if (cityName.equals("Milan")){
                nome_citta = "Milano";
            }
            else if (cityName.equals("Turin")){
                nome_citta = "Torino";
            }else if (cityName.equals("New York")){
                nome_citta = "NewYorkCity";
            }else if (cityName.equals("Los Angeles")){
                nome_citta = "LosAngeles";
            }
            else if (cityName.equals("San Diego")){
                nome_citta = "SanDiego";
            }
            else if (cityName.equals("Twin Cities")){
                nome_citta = "TwinCities";
            }
            else if (cityName.equals("Vienna")) {
                nome_citta = "wien";

            }
            else if (cityName.equals("Munich")) {
                nome_citta = "München";
            }
            else if (cityName.equals("Osler")) {
                nome_citta = "Rheinland";
            }
            // Controllo formattazione JCDecaux
            else if (cityName.equals("Valencia")) {
                nome_citta_test = "Valence";
            }
            else if (cityName.equals("Parigi")) {
                nome_citta_test = "Paris";
            }
            else if (cityName.equals("Besançon")){
                nome_citta_test = "Besancon";
            }
            else if (cityName.equals("Créteil")) {
                nome_citta_test = "Creteil";
            }
            else {
                nome_citta = cityName;
                nome_citta_test = cityName;
            }
        }
        else {

        }
    } catch (IOException e) {
        e.printStackTrace();

    }

在我的地图上为我的位置设置了此权限:

if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
                .PERMISSION_GRANTED && ActivityCompat
                .checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager
                .PERMISSION_GRANTED) {

            /*Toast.makeText(getActivity(),
                    "Need location permission for   map.setMyLocationEnabled(true);",
                    Toast.LENGTH_LONG).show();*/

            MultiplePermissionsListener snackbarMultiplePermissionsListener =
                    SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
                            .with((ViewGroup) getView(), "La app ha bisogno di ablitare i permessi di localizzaione per mostrare la mappa")
                            .withOpenSettingsButton("Settings")
                            .withCallback(new Snackbar.Callback() {
                                @Override
                                public void onShown(Snackbar snackbar) {
                                    // Event handler for when the given Snackbar has been dismissed
                                }

                                @Override
                                public void onDismissed(Snackbar snackbar, int event) {
                                    // Event handler for when the given Snackbar is visible
                                }
                            })
                            .build();
            Dexter.checkPermissions(snackbarMultiplePermissionsListener, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.GET_ACCOUNTS);
            return;
        }

这是我的GPSTracker.java类:

public final class GPSTracker implements LocationListener {

private final Context mContext;

// flag for GPS status
public boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

/**
 * Function to get the user's current location
 *
 * @return
 */
public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        Log.v("isGPSEnabled", "=" + isGPSEnabled);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        Log.v("isNetworkEnabled", "=" + isNetworkEnabled);

        if (isGPSEnabled == false && isNetworkEnabled == false) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                location=null;
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                location=null;
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
      //                                DecimalFormat latitude = new                  DecimalFormat("00.00");
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 *
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle(R.string.title);

    // Setting Dialog Message
    alertDialog
            .setMessage(R.string.subtitle);

    // On pressing Settings button
    alertDialog.setPositiveButton(R.string.impostazioni,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

    // on pressing cancel button
    alertDialog.setNegativeButton(R.string.cancella,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    alertDialog.setCancelable(false);

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

}

另外我注意到在API 23上使用场所选择器我发现了这个错误: 尝试在空对象引用上调用接口方法'int java.util.List.size()' 对于此代码:

if (resultCode == getActivity().RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(getActivity(), data);
                String addresses = place.getAddress().toString();
                if (addresses != null) {
                    puntoA.setText(addresses);
                }if (addresses.isEmpty()){
                    addresses = "(" + place.getLatLng().latitude + "," + place.getLatLng().longitude + ")";
                    puntoA.setText("nessun indirizzo disponibile " + addresses);

                }
                //puntoA.setText(addresses);
                // Recupero coordinate
                Geocoder geocoder = new Geocoder(getActivity());
                List<Address> address = null;
                try {
                    address = geocoder.getFromLocationName(addresses, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(address.size() > 0) {
                    Lat = address.get(0).getLatitude();
                    Lon = address.get(0).getLongitude();
                }
                else if (address.size() == 0) {
                    Lat = place.getLatLng().latitude;
                    Lon = place.getLatLng().longitude;
                }

但此功能在其他API版本上也能很好地工作 有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

现在我的代码在API 23上工作正常,我使用此代码:

// To get City-Name from coordinates
    GPSTracker gpsTracker = new GPSTracker(getActivity());
    Double LatFab = gpsTracker.getLatitude();
    Double LonFab = gpsTracker.getLongitude();

    List<Address> geocodeMatchess = null;
    String Country_;

    try {
        geocodeMatchess = new Geocoder(getActivity(), Locale.ENGLISH).getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
        if (geocodeMatchess.isEmpty()) {

        }else {
            Country_ = geocodeMatchess.get(0).getLocality();
            citta_fab = Country_;
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

希望你帮忙