使用 getFromLocation 将坐标转换为地址时出现反向地理编码问题

Trouble in reverse Geo-coding while converting co-ordinates to address using getFromLocation

我在使用 getFromLocation 反转地理编码时遇到问题。 我正在使用 Android Studio 并通过设备监视器传递坐标。

坐标显示正常,但地址仍然是空的。

我在 Whosebug 上尝试了很多解决方案,即使已知 none 崩溃,我仍然无法获取地址。

这是代码片段。我在用

@Override
    public void onLocationChanged(Location location){
        double lat = (location.getLatitude());
        double lng = (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));


    //Get address base on location
    try{
        Geocoder geo = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = geo.getFromLocation(lat, lng, 1);
        if (addresses.isEmpty()) {
            endereco.setText("Waiting for Location");
        }
        else {
            if (addresses.size() > 0) {
                Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());

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

在 Geocoder 线上,我也试过这个

Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault());

如果需要,这里是整个activity

的代码
import android.app.Activity;
import android.content.Context;
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.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;

/**
 * Created by Usuário on 05/02/2015.
 */
public class GPSActivity extends Activity implements LocationListener {
    private static final String TAG = null;
    private TextView latituteField;
    private TextView longitudeField;
    private TextView endereco;
    private LocationManager locationManager;
    private String provider;

    /**
     * Called when the activity is first created.
     */

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gps);
        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);
        endereco = (TextView) findViewById(R.id.Endereco);

        //Get the Location Manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //Define the criteria how to select location provider -> use
        // default

        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria,false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null){
            System.out.println("Provider " + provider + " has been selected");
            onLocationChanged(location);
        }else{
            latituteField.setText("Locação não disponível");
            longitudeField.setText("Locação não disponível");
        }
    }

    /**
     * Request updates at startup
     */
    @Override
    protected void onResume(){
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /**
     * Remove the LocationListener updates when Activity is paused
     */
    @Override
    protected void onPause(){
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location){
        double lat = (location.getLatitude());
        double lng = (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));


        //Get address base on location
        try{
            Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault());
            List<Address> addresses = geo.getFromLocation(lat, lng, 1);
            if (addresses.isEmpty()) {
                endereco.setText("Waiting for Location");
            }
            else {
                if (addresses.size() > 0) {
                    Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());

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




    @Override
    public void onStatusChanged(String provider, int status, Bundle extras){
        //TODO Auto-generated method tub
    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }



}

我对代码进行了一些更改并设法让它工作。

解决问题的是位

char[] buffer = new char[2048];
                Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
                while (true) {
                    int n = reader.read(buffer);
                    if (n < 0) {
                        break;
                    }
                    stringBuilder.append(buffer, 0, n);
                }

但是由于我更改了很多东西,所以我将 post 下面是完整的代码。

package br.com.agenciaeisberg.qm;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * Created by Usuário on 05/02/2015.
 */
public class GPSActivity extends Activity implements LocationListener {
    private TextView latituteField;
    private TextView longitudeField;
    private TextView endereco;
    private LocationManager locationManager;
    private String provider;

    /**
     * Called when the activity is first created.
     */

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gps);
        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);
        endereco = (TextView) findViewById(R.id.Endereco);

        //Get the Location Manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //Define the criteria how to select location provider -> use
        // default

        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria,false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null){
            System.out.println("Provider " + provider + " has been selected");
            onLocationChanged(location);
        }else{
            latituteField.setText("Locação não disponível");
            longitudeField.setText("Locação não disponível");
        }
    }

    /**
     * Request updates at startup
     */
    @Override
    protected void onResume(){
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /**
     * Remove the LocationListener updates when Activity is paused
     */
    @Override
    protected void onPause(){
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location){
        double lat = (location.getLatitude());
        double lng = (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));


        // Encontrando Endereço
        new EncontrarEndereco().execute();

    }




    @Override
    public void onStatusChanged(String provider, int status, Bundle extras){
        //TODO Auto-generated method tub
    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    class EncontrarEndereco extends AsyncTask<String, String, JSONObject> {

        ProgressDialog pDialog = new ProgressDialog(GPSActivity.this);

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog.setMessage("Aguarde, enquanto buscamos seu endereço");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }


        double lat = -19.971864410192393;
        double lng = -43.97544760674483;

        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true&language=pt&region=BR&output=xml&oe=utf8");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        protected JSONObject doInBackground (String... args){
            try {
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();

                char[] buffer = new char[2048];
                Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
                while (true) {
                    int n = reader.read(buffer);
                    if (n < 0) {
                        break;
                    }
                    stringBuilder.append(buffer, 0, n);
                }


                int b;
                while ((b = reader.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject = new JSONObject(stringBuilder.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject;
        }

        protected void onPostExecute(final JSONObject jsonObject) {
            // Dismiss a caixa de dialogo depois de buscar todos os items


            String numero;
            String rua;
            String bairro;
            String cidade;
            String estado;
            String pais;
            String endereco_compelto;

            pDialog.dismiss();

            Log.i("JSON string =>", jsonObject.toString());

            try {
                String status = jsonObject.getString("status");
                Log.i("status", status);

                if(status.equalsIgnoreCase("OK")){
                    JSONArray results = jsonObject.getJSONArray("results");

                    JSONObject r = results.getJSONObject(0);
                    JSONArray addressComponentsArray = r.getJSONArray("address_components");

                    JSONObject addressComponents = addressComponentsArray.getJSONObject(0);
                    numero = addressComponents.getString("short_name");
                    Log.i("Número", numero);

                    JSONObject addressComponents1 = addressComponentsArray.getJSONObject(1);
                    rua = addressComponents1.getString("long_name");
                    Log.i("Rua", rua);

                    JSONObject addressComponents2 = addressComponentsArray.getJSONObject(2);
                    bairro = addressComponents2.getString("long_name");
                    Log.i("Bairro ", bairro);

                    JSONObject addressComponents3 = addressComponentsArray.getJSONObject(3);
                    cidade = addressComponents3.getString("long_name");
                    Log.i("Cidade ", cidade);

                    JSONObject addressComponents5 = addressComponentsArray.getJSONObject(5);
                    estado = addressComponents5.getString("short_name");
                    Log.i("Estado ", estado);

                    JSONObject addressComponents6 = addressComponentsArray.getJSONObject(6);
                    pais = addressComponents6.getString("long_name");
                    Log.i("Pais ", pais);

                    endereco_compelto = rua + ", " + numero + " - " + bairro + ", " + cidade + " - " + estado + ", " + pais;

                    endereco.setText(endereco_compelto);

                }




            }catch (JSONException e) {
                Log.e("testing","Failed to load JSON");
                e.printStackTrace();
            }


        }


    }


}