I wonder how I put a "Wait" animation while doing a heavy task on Android. In case, when the user type the zip I want to run an animation asking to wait while I make the request.
private Activity context;
private ProgressDialog progress;
private class BuscaCepTask extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
progress = ProgressDialog.show(context, "Aguarde...", "Buscando CEP...", true, true);
}
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);
EditText rua = (EditText) findViewById(R.id.rua);
rua.setText(object.getString("logradouro"));
} catch (JSONException e) {
e.printStackTrace();
}
progress.dismiss();
}
}
.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.formulario);
final EditText endereco = (EditText) findViewById(R.id.endereco);
endereco.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
BuscaCepTask buscarCep = new BuscaCepTask();
buscarCep.execute(endereco.getText().toString());
}
});