0
Any automatic search method for the address from the current location of the user? No need to fill in the address fields. Informing the zip code or clicking a search button.
0
Any automatic search method for the address from the current location of the user? No need to fill in the address fields. Informing the zip code or clicking a search button.
1
Take a look at the class Geocoder and its method getFromLocation.
Has a complete example on the site for Android developers, but, in short, it’s something like:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException ioException) {
Log.e(TAG, "Serviço indisponível", ioException);
} catch (IllegalArgumentException illegalArgumentException) {
Log.e(TAG, "Localização inválida", illegalArgumentException);
}
if(addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
// Esse é o endereço.
}
For more details, and a full functional example, I recommend reading of the guide
Please, if you can be more clear in your answer, because only this snippet of code does not solve the problem. Also indicate the guides for consultation is more characterized as comment than as an effective response. If possible put a code of own authorship, so that it is understood the solution as a whole.
1
Well, I’ll split my answer into two parts:
cep.setOnFocusChangeListener(OnFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
if(Utils.validCep(cep.text.toString())){
//Request para o serviço de consulta do CEP
}
}
})
where: the zip code is mine EditText
. I used the method OnFocusChangeListener
in this case because the way I set up my form, was the most suitable in my vision. But you can control via IMEOptions
or TextChangedListener
, however you prefer.
I will also leave the function that validates the zip code below.
fun validCep(cep: String): Boolean {
val pattern = Pattern.compile("^[0-9]{5}-[0-9]{3}$")
val matcher = pattern.matcher(cep)
return matcher.find()
}
I like to use the Viacep to do this.
Just send a request to the address viacep.com.br/ws/01001000/json/
, where 01001000 would be the zip code to consult, and it returns you a JSON in this format:
{
"cep": "01001-000",
"logradouro": "Praça da Sé",
"complemento": "lado ímpar",
"bairro": "Sé",
"localidade": "São Paulo",
"uf": "SP",
"unidade": "",
"ibge": "3550308",
"gia": "1004"
}
Just you take the return and set to the address fields pro your form in case of return 200
.
If you do not have a form to enter the zip code, the best way is to follow the answer using Geocoder, where you would get the location of the device for consultation.
Browser other questions tagged java android
You are not signed in. Login or sign up in order to post.
Use the user’s gps
– Woton Sampaio