Как получить информацию о городе в Android по долготе и широте

Я делаю приложение для Android сейчас. У меня возникла проблема с получением местоположения.

В моем коде я заставил свое приложение получать долготу и широту по GPS. Однако я по-прежнему не могу получить название города по долготе и широте. Я не знаю, почему мой код попадает в Exception, хотя в моем коде нет неправильных вещей.

Вот мой код для получения названия города

    ackage org.androidtown.getcurrentlocation;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

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

public class GetCurrentLocation extends AppCompatActivity implements View.OnClickListener {
    private LocationManager locationManager = null;
    private LocationListener locationListener = null;

    private Button btnGetLocation = null;
    private EditText editLocation = null;
    private ProgressBar pb = null;

    private static final String TAG = "Debug";
    private Boolean flag = false;

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

        pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.INVISIBLE);

        editLocation = (EditText) findViewById(R.id.editTextLocation);

        btnGetLocation = (Button) findViewById(R.id.btnLocation);
        btnGetLocation.setOnClickListener(this);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        flag = displayGpsStatus();
        if (flag) {
            Log.v(TAG, "onClick");

            editLocation.setText("Please!! move your device to see the changes in coordinates.\nWait..");

            pb.setVisibility(View.VISIBLE);
            locationListener = new MyLocationListener();
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

            }
        else{
            alertbox("GPS Status!!", "Your GPS is : OFF");
        }
    }

    private Boolean displayGpsStatus(){
        ContentResolver contentResolver = getBaseContext().getContentResolver();
        boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
        if(gpsStatus){
            return true;
        }
    else{
            return false;
        }
    }

    protected void alertbox(String title, String mymessage){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your Device's GPS is Disable").setCancelable(false).setTitle("**GPS Status**").setPositiveButton("Gps On", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent myIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
                startActivity(myIntent);
                dialog.cancel();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private class MyLocationListener implements LocationListener{
        @Override
        public void onLocationChanged(Location loc){
            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(getBaseContext(), "Location changed : Lat " + loc.getLatitude() +"Lng: "+loc.getLongitude(),
                    Toast.LENGTH_SHORT).show();
            String longtitude = "Longtitude: "+loc.getLongitude();
            Log.v(TAG, longtitude);
            String latitude = "Latitude: "+loc.getLatitude();
            Log.v(TAG, latitude);


            String cityName = "default";
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            // addresses
            try{
                List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
                if(addresses.size()>0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            }catch(IOException e){
                e.printStackTrace();
            }

            String s = longtitude + "\n" + latitude +
                    "\n\nMy Current City is : "+ cityName;
                    editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider){

        }

        @Override
        public void onProviderEnabled(String provider){

        }

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

        }



    }
}

В приведенном выше коде эта часть является основным кодом для получения названия города по долготе и широте. Нет никакой проблемы, чтобы получить долготу и широту. Единственная проблема - получить название города.

String cityName = "default";
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            // addresses
            try{
                List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
                if(addresses.size()>0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            }catch(IOException e){
                e.printStackTrace();
            }

            String s = longtitude + "\n" + latitude +
                    "\n\nMy Current City is : "+ cityName;
                    editLocation.setText(s);
        }

Спасибо, что прочитали мой вопрос. Хорошего дня (?) Полночь.


person Wongeun Cho    schedule 05.06.2017    source источник
comment
Не могли бы вы опубликовать исключение?   -  person Saurabh7474    schedule 05.06.2017
comment
Исключение генерируется нижеуказанными адресами кода, не имеющими List‹Address› . Это означает, что он не инициализирован. List‹Address› addresss = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);   -  person Wongeun Cho    schedule 05.06.2017
comment
Используйте API Google Search Places для получения адресов.   -  person Ashish Pardhiye    schedule 05.06.2017
comment
Вместо геокодера (который может давать исключения во время) используйте API-интерфейсы местоположения от Google, чтобы получить адрес местоположения из lat lng.   -  person Dr. aNdRO    schedule 05.06.2017
comment
Спасибо, ребята, я попробую использовать Google API!   -  person Wongeun Cho    schedule 05.06.2017


Ответы (1)


person    schedule
comment
Я думаю, что мой параметр «Местоположение» получает значение «Местоположение», где оно вызывается. Я могу понять, что значение Location инициализировано, потому что loc.getLongitude() и loc.getLatitude работают. Спасибо за ваш ответ. - person Wongeun Cho; 05.06.2017
comment
Извините, я не понял, что вы пытаетесь сказать здесь. разве ваш вопрос не был о том, что у вас есть широта/долгота, но вы не можете получить из него название города ?? - person sumit; 05.06.2017