Gostaria de pedir aos conhecedores de Java (Android) que me orientassem nesse código:
MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("TESTE", "Iniciou MainActivity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
txt_usuario = (EditText) findViewById(R.id.usuario);
txt_senha = (EditText) findViewById(R.id.senha);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String user = txt_usuario.getText().toString();
String pssw = txt_senha.getText().toString();
SistemaHttp sHttp = new SistemaHttp(getBaseContext());
String ret = sHttp.retornaUsuario(user, pssw);
retornoLogin(ret);
}
});
}
private void retornoLogin(String retorno)
{
Log.d("TESTE", "(MainActivity) retornoLogin(" + retorno + ")");
if (retorno.equals("OK"))
{
Toast.makeText(this, "Logado com sucesso", Toast.LENGTH_SHORT).show();
}
else if (retorno.equals("ERRO"))
{
Toast.makeText(this, "Login incorreto", Toast.LENGTH_SHORT).show();
}
}
SistemaHttp:
public static final String SERVIDOR = "http://www.exemplo.com.br";
private static final String WEBSERVICE_URL = SERVIDOR + "/webservicesistema.php";
private Context mContext;
public SistemaHttp(Context ctx)
{
mContext = ctx;
}
public String retornaUsuario(String user, String pssw)
{
Log.d("TESTE", "(SistemaHttp) retornaUsuario(" + user + ", " + pssw + ")");
String met = "GET";
String resp = "";
try
{
if (enviarRequisicao(met, user, pssw))
{
resp = "OK";
Log.d("TESTE", "(SistemaHttp) retornaUsuario() enviarRequisicao(" + met + ", " + user + ", " + pssw + ") OK");
}
else
{
resp = "ERRO";
}
}catch (Exception e)
{
e.printStackTrace();
}
return resp;
}
private boolean enviarRequisicao(String metodoHttp, String user, String pssw) throws Exception
{
Log.d("TESTE", "(SistemaHttp) enviarRequisicao(" + metodoHttp + ", " + user + ", " + pssw + ")");
boolean sucesso = false;
boolean doOutput = !"DELETE".equals(metodoHttp);
String url = WEBSERVICE_URL;
HttpURLConnection conexao = abrirConexao(url, metodoHttp, doOutput);
if (doOutput)
{
OutputStream os = conexao.getOutputStream();
os.write(loginToJsonBytes(user, pssw));
os.flush();
os.close();
}
int responseCode = conexao.getResponseCode();
Log.d("TESTE", "(SistemaHttp) enviarRequisicao() responseCode == " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK)
{
Log.d("TESTE", "(SistemaHttp) enviarRequisicao() responseCode == HttpURLConnection.HTTP_OK");
InputStream is = conexao.getInputStream();
String s = streamToString(is);
is.close();
// JSONObject json= new JSONObject(s);
// hotel.idServidor = json.getInt("id");
sucesso = true;
}
else
{
Log.d("TESTE", "(SistemaHttp) enviarRequisicao() responseCode == HttpURLConnection.ERROR");
sucesso = false;
}
conexao.disconnect();
return sucesso;
}
private HttpURLConnection abrirConexao(String url, String metodo, boolean doOutput) throws Exception
{
Log.d("TESTE", "(SistemaHttp) abrirConexao(" + url + ", " + metodo + ", " + doOutput + ")");
URL urlCon = new URL(url);
HttpURLConnection conexao = (HttpURLConnection) urlCon.openConnection();
conexao.setReadTimeout(15000);
conexao.setConnectTimeout(15000);
conexao.setRequestMethod(metodo);
conexao.setDoInput(true);
conexao.setDoOutput(doOutput);
if (doOutput)
{
conexao.addRequestProperty("Content-Type", "application/json");
}
conexao.connect();
return conexao;
}
private byte[] loginToJsonBytes(String user, String pssw) {
Log.d("TESTE", "(SistemaHttp) loginToJsonBytes(" + user + ", " + pssw + ")");
try {
JSONObject jsonLogin = new JSONObject();
jsonLogin.put("usuario", user);
jsonLogin.put("senha", pssw);
String json = jsonLogin.toString();
return json.getBytes();
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
private String streamToString(InputStream is) throws Exception {
Log.d("TESTE", "(SistemaHttp) Iniciou streamToString()");
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0)
{
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
A logica é a seguinte, ao clicar no botão pegar os valores que foram preenchidos nos EditTexts
e enviar para o metodo retornaUsuario(user, pssw)
da classe SistemaHttp, onde ela pega os dados e faz uma requisição HTTP para o webservice.php e retorna se existe o usuario e senha no banco de dados, e o metodo retornoLogin da MainActivity exibe um Toast de acordo com o retorno.
O trecho do webservice.php
esta aqui:
$metodoHttp = $_SERVER['REQUEST_METHOD'];
if ($metodoHttp == 'GET') {
$stmt = $conn->prepare(
"SELECT * FROM hotel_db.usuarios WHERE login=? and senha=?");
$json = json_decode(file_get_contents('php://input'));
$endereco = $json->{'login'};
$estrelas = $json->{'senha'};
$stmt->bind_param("ss", $nome, $login);
$stmt->execute();
$stmt->close();
$id = $conn->insert_id;
$jsonRetorno = array("id"=>$id);
echo json_encode($jsonRetorno);
}
Na parte do Android coloquei uns logs para ver ate onde o código rodava e ele chega ate o método abrirConexao()
e aparece uma mensagem azul escrito:
W/System.err: android.os.NetworkOnMainThreadException W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:418) W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215) W/System.err: at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29) W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232) W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124) W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272) W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211) W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382) W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106) W/System.err: at com.exemplo.exemplo.SistemaHttp.abrirConexao(SistemaHttp.java:122) W/System.err: at com.exemplo.exemplo.SistemaHttp.enviarRequisicao(SistemaHttp.java:72) W/System.err: at com.exemplo.exemplo.SistemaHttp.retornaUsuario(SistemaHttp.java:45) W/System.err: at com.exemplo.exemplo.MainActivity$1.onClick(MainActivity.java:44) W/System.err: at android.view.View.performClick(View.java:4780) W/System.err: at android.view.View$PerformClick.run(View.java:19866) W/System.err: at android.os.Handler.handleCallback(Handler.java:739) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95) W/System.err: at android.os.Looper.loop(Looper.java:135) W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254) W/System.err: at java.lang.reflect.Method.invoke(Native Method) W/System.err: at java.lang.reflect.Method.invoke(Method.java:372) W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)