User Login with WebService

1

I would like to ask Java connoisseurs (Android) to guide me in this code:

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();
    }
}

SystemHttp:

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());
}

The logic is as follows when clicking on the button to get the values that were filled in the EditTexts and send to the retornaUsuario(user, pssw) method of the SystemHttp class, where it takes the data and makes an HTTP request for the webservice.php and returns if the user and password exist in the database, and the MainActivityLogin return method displays a Toast according to the return.

The webservice.php snippet is here:

$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);
} 

In the Android part I put some logs to see where the code was running and it gets to the abrirConexao() method and a blue message appears:

  

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.example.example.Host.Host.Upper (SystemHttp.java:122)   W / System.err: at   com.example.example.SystemHttp. sendRequisition (SystemHttp.java:72)   W / System.err: at   com.example.example.SystemHttp.UserReport (SystemHttp.java:45)   W / System.err: at   com.example.example.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)

    
asked by anonymous 17.03.2016 / 20:33

1 answer

1

As of Android 3.0 , no more connections are allowed (also known as UI Thread ). Network operations in this thread have the effect of freezing the graphical interface until the request returns a result, which provides a bad user experience.

One solution is to make your operation within AsyncTask .

I will not repeat how to do this, because here in StackOverflow in Portuguese we already have an explanation of how do. The official documentation also has an easy-to-understand example. If you are experiencing difficulties, feel free to open a new question.

    
18.03.2016 / 00:47