How to validate a zip on Android?

1

I would like to know the best way to do the validation of cep on Android. I have a form that the user types the zip and want to return on the screen whether it is valid or not. And if possible return the address. I saw that the mail has a JSON api that returns the address from the zip, but wanted to know how to implement it on my system.

link {CEP} .json

    
asked by anonymous 18.05.2015 / 19:03

1 answer

3

First of all, to be clear this API you reported is not official to the Correiros . This has been a well-discussed subject here and here about an efficient way to get this data.

Now, if you really want to use the source of this site, just make a simple call with the class HttpURLConnection (in a different thread of course) and get the result, which is a JSON object. Something like this:

private class BuscarCepTask extends AsyncTask<String, Void, String> {
    URL url = null;
    HttpURLConnection httpURLConnection = null;

    @Override
    protected String doInBackground(String... params) {
        StringBuilder result = null;
        int respCode = -1;

        try {
            url = new URL("http://cep.correiocontrol.com.br/" + params[0] + ".json");
            httpURLConnection = (HttpURLConnection) url.openConnection();

            do {
                if (httpURLConnection != null) {
                    respCode = httpURLConnection.getResponseCode();
                }
            } while (respCode == -1);

            if (respCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                result = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                }
                br.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
                httpURLConnection = null;
            }
        }

        return (result != null) ? result.toString() : null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try {
            JSONObject object = new JSONObject(s);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

And make the call like this:

BuscarCepTask buscarCep = new BuscarCepTask();
buscarCep.execute("02011200");

The result that is in the onPostExecute method comes in the object which is a JSONObject , just search for object.getString("logradouro") and any other key you have in the object.

    
18.05.2015 / 19:56