3

So, I'm trying to login into my adroid app using data from my mysql database, and the Android Studio returned me this messages in the terminal. Follow bellow the code that I'm using in the Android Studio and the terminal messages. I wrote the ip address and port with " ** " for security reasons.

Someone could help me to understand what's going on?

LoginActivity.java

package com.pedido.meu.telas_meu_pedido.controller;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.pedido.meu.telas_meu_pedido.R;
import com.pedido.meu.telas_meu_pedido.modelo.AssyncLogin;

public class LoginActivity extends AppCompatActivity
{
    private EditText editTextUsername, editTextPassword;
    private Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        editTextUsername = findViewById(R.id.txtLogin);
        editTextPassword = findViewById(R.id.txtPassword);
        btnLogin = findViewById(R.id.btnLogin);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String username = editTextUsername.getText().toString().trim();
                final String password = editTextPassword.getText().toString().trim();

                new AssyncLogin(LoginActivity.this).execute(username, password);
            }
        });
    }

}

AssyncLogin.java

package com.pedido.meu.telas_meu_pedido.modelo;

import com.pedido.meu.telas_meu_pedido.controller.ListaProdutosActivity;
import com.pedido.meu.telas_meu_pedido.controller.LoginActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class AssyncLogin extends AsyncTask<String, String, String>
{
    private LoginActivity loginActivity;
 //   ProgressBar progressBarLoading = new ProgressBar(loginActivity);
    HttpURLConnection conn;
    URL url = null;

    public AssyncLogin(LoginActivity loginActivity) {
        this.loginActivity = loginActivity;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
     //   progressBarLoading.draw();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            url = new URL("http://192.168.15.12/magnero/login.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("username", params[0])
                    .appendQueryParameter("password", params[1]);
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

    //    pdLoading.dismiss();

        if (result.equalsIgnoreCase("true")) {
            Intent intent = new Intent(loginActivity, ListaProdutosActivity.class);
            loginActivity.startActivity(intent);
            loginActivity.finish();

        } else if (result.equalsIgnoreCase("false")) {

            // If username and password does not match display a error message
            Toast.makeText(loginActivity, "Invalid userename or password", Toast.LENGTH_LONG);

        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            Toast.makeText(loginActivity, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG);

        }
    }    
}

login.php

<?php

    include 'conexao.php';
    $result='';
     if(isset($_POST['username']) && isset($_POST['password']))
     {


          $username = $_POST['username'];
          $password = $_POST['password'];


          $sql = 'SELECT * FROM afiliado WHERE  email = :username AND senha = :password';
          $stmt = $conn->prepare($sql);
          $stmt->bindParam(':email', $username, PDO::PARAM_STR);
          $stmt->bindParam(':senha', $password, PDO::PARAM_STR);
          $stmt->execute();
          if($stmt->rowCount())
          {
          $result="true";   
          }  
          elseif(!$stmt->rowCount())
          {
            $result="false";
          }

            echo $result;
   }

?>

conexao.php

<?php
define('hostname', 'https://auth-db100.hostinger.com.br/index.php');
define('user', 'user');
define('password', 'password');
define('databaseName', 'database_mysql');
$connect = mysqli_connect(hostname, user, password, databaseName);
?>

Terminal Messages

No Network Security Config specified, using platform default
W/System.err: java.net.SocketTimeoutException: failed to connect to /******* (port ***) from /********** (port ****) after 10000ms
W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:185)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:129)
        at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
        at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:26)
W/System.err:     at com.pedido.meu.telas_meu_pedido.modelo.AssyncLogin.doInBackground(AssyncLogin.java:70)
W/System.err:     at com.pedido.meu.telas_meu_pedido.modelo.AssyncLogin.doInBackground(AssyncLogin.java:21)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err:     at java.lang.Thread.run(Thread.java:764)
Luke
  • 150
  • 11
  • 2
    Way too much code, peeps are unlikely to prod through all that. Read all about a **[minimal, complete, verifiable example (MCVE)](https://stackoverflow.com/help/mcve)** and try to distill this to the essense of your issue. – YvesLeBorg Jan 21 '19 at 15:54
  • finally : if this code is real, you seem to run your php on a 'local net host', yet your connexao indicates the DB is remote, hosted out there. Usually, you need to declare properly the clients (your php code) and their hosts within the DB users, in order to be able to successfully connect. – YvesLeBorg Jan 21 '19 at 15:57
  • I declared on my computer, but for safety reasons I changed the credentials here. – Luke Jan 21 '19 at 15:59
  • in connexao, you say 'hostname' , yet you indicate an `index.php` url. That wont fly, your connect will fail for sure. it truly needs to be a 'hostname' which can be resolved by your DNS chain. – YvesLeBorg Jan 21 '19 at 16:02
  • 1
    **Never store passwords in clear text!**. Only store password hashes. Use PHP's [`password_hash()`](http://php.net/manual/en/function.password-hash.php) and [`password_verify()`](http://php.net/manual/en/function.password-verify.php) . If you're running a PHP version lower than 5.5 (which I _really_ hope you aren't), you can use the [password_compat library](https://github.com/ircmaxell/password_compat) to get the same functionallity. – M. Eriksson Jan 21 '19 at 16:18
  • You should also read [the manual](http://php.net/manual/en/pdostatement.rowcount.php) about `$stmt->rowCount()`. _"If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications."_ – M. Eriksson Jan 21 '19 at 16:20
  • I didn't get the point form the hostname thing. And About the password, I'm really so noob in php, just using now because I need to connect to my mysql database, so I can't tell you what version I', using and I don't know how to use the piece of code that you're metioned. – Luke Jan 21 '19 at 16:27
  • 1
    **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/master/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text** or a weak hash like **SHA1 or MD5**. – tadman Jan 21 '19 at 18:09
  • If this is code that's going to be deployed and used by real people to store their passwords it doesn't matter if you're "noob" or not, you're responsible for storing those passwords securely. There's nothing wrong with being new and learning. There is a lot of thing wrong with not following basic security practices and making it possible for your application to leak plain-text passwords. – tadman Jan 21 '19 at 18:09

0 Answers0