Open maiaramendes opened 6 years ago
package br.edu.etep.victor.viacep_androidetep;
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.EditText;
import java.util.regex.Matcher; import java.util.regex.Pattern;
import br.com.jansenfelipe.androidmask.MaskEditTextChangedListener; import viacep.ViaCEP;
public class PainelActivity extends AppCompatActivity implements Button.OnClickListener {
private Button btnBuscar;
private EditText txtCEP;
private EditText txtLogradouro;
private EditText txtComplemento;
private EditText txtBairro;
private EditText txtLocalidade;
private EditText txtUf;
private EditText txtIbge;
private EditText txtGia;
private ViaCEP vCEP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_painel);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Adaptado por Victor Machado", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// define
//this.vCEP = null;
// referência
this.btnBuscar = (Button) findViewById(R.id.btnBuscar);
this.txtCEP = (EditText) findViewById(R.id.txtCEP);
this.txtLogradouro = (EditText) findViewById(R.id.txtLogradouro);
this.txtComplemento = (EditText) findViewById(R.id.txtComplemento);
this.txtBairro = (EditText) findViewById(R.id.txtBairro);
this.txtLocalidade = (EditText) findViewById(R.id.txtLocalidade);
this.txtUf = (EditText) findViewById(R.id.txtUf);
this.txtIbge = (EditText) findViewById(R.id.txtIbge);
this.txtGia = (EditText) findViewById(R.id.txtGia);
// cria a máscara
MaskEditTextChangedListener maskCEP = new MaskEditTextChangedListener("#####-###", this.txtCEP);
// adiciona a máscara no objeto
this.txtCEP.addTextChangedListener(maskCEP);
// define o evento de clique
this.btnBuscar.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// evento para buscar um cep
if (view == this.btnBuscar) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// limpa
//limpar todos campos
// cep
String cep = this.txtCEP.getText().toString();
// verifica se o CEP é válido
Pattern pattern = Pattern.compile("^[0-9]{5}-[0-9]{3}$");
Matcher matcher = pattern.matcher(cep);
if (matcher.find()) {
new DownloadCEPTask().execute(cep);
} else {
//JOptionPane.showMessageDialog(null, "Favor informar um CEP válido!", "Aviso!", JOptionPane.WARNING_MESSAGE);
new AlertDialog.Builder(this)
.setTitle("Aviso!")
.setMessage("Favor informar um CEP válido!")
.setPositiveButton(R.string.msgOk, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// nada
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
} else {
new AlertDialog.Builder(this)
.setTitle("Sem Internet!")
.setMessage("Não tem nenhuma conexão de rede disponível!")
.setPositiveButton(R.string.msgOk, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// nada
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_painel, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DownloadCEPTask extends AsyncTask<String, Void, ViaCEP> {
@Override
protected ViaCEP doInBackground(String ... ceps) {
ViaCEP vCep = null;
try {
vCep = new ViaCEP(ceps[0]);
} finally {
return vCep;
}
}
@Override
protected void onPostExecute(ViaCEP result) {
if (result != null) {
//fazer exibir
}
}
}
}
Obtem um CEP no ViaCEP */ package viacep;
import android.widget.Toast;
import org.json.JSONException; import org.json.JSONObject;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL;
/**
*/ public class ViaCEP {
private String CEP; private String Logradouro; private String Complemento; private String Bairro; private String Localidade; private String Uf; private String Ibge; private String Gia;
/**
/**
/**
@throws viacep.ViaCEPException caso ocorra algum erro */ public final void buscar(String cep) { this.CEP = cep;
// define a url String url = "http://viacep.com.br/ws/" + cep + "/json/";
// define os dados try { JSONObject obj = new JSONObject(this.get(url));
if (!obj.has("erro")) { this.CEP = obj.getString("cep"); this.Bairro = obj.getString("bairro"); //outros
} else { throw new ViaCEPException("Não foi possível encontrar o CEP", cep); } }catch (Exception ex) { new ViaCEPException("Não foi feito tratamento", cep); } }
/**
/**
/**
/**
/**
/**
/**
/**
/**
@throws viacep.ViaCEPException caso ocorra algum erro */ public final String get(String urlToRead) throws ViaCEPException { StringBuilder result = new StringBuilder();
try { URL url = new URL(urlToRead); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET");
} catch (MalformedURLException | ProtocolException ex) { throw new ViaCEPException(ex.getMessage()); } catch (IOException ex) { throw new ViaCEPException(ex.getMessage()); }
return result.toString(); } }