2016-07-27 100 views
2

我开发的应用程序在运行时使用lat和long使用GPSTracker.java类的城市名称,并将此城市名称添加到url以检索json数据。 我的代码工作非常细,从API 18〜API 22,但现在当我在API 23我的代码运行的地理编码器不工作,城市名称是空 这是我的主要活动代码retrive城市名称:Android Geocoder无法在API 23上工作

// 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的地方选择器我recive此错误: 尝试调用接口方法“诠释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版本上工作得很好 请帮忙吗?

+0

你得到任何这解决方案?我面临同样的问题 – VVB

回答

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(); 
    } 

希望这HEL你