Login problems with mysql, php, Android

Asked

Viewed 103 times

0

So, guys, I’m trying to perform the login feature on my Adroid app. I am using android native Java, mysql and php, but I can not login to the application, and Android Studio does not return me any error.

Could someone take a look at my code and point out what might be wrong, or missing?

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();
                final String password = editTextPassword.getText().toString();

                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;
    HttpURLConnection conn;
    URL url = null;

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

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


    }

    @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) {


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

        }
    }

}

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:orientation="vertical"
        >

                    <!-- Título da tela -->
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@mipmap/ic_login"
            android:layout_gravity="center"
            android:layout_marginBottom="20dp"
            />

        <TextView
            android:id="@+id/txtTituloLogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/txtTituloLogin"
            android:textColor="@color/colorPrimary"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:textSize="30dp"
            android:layout_marginBottom="50dp"
            />

                    <!-- Formulário da tela -->
        <EditText
            android:id="@+id/txtLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login"
            android:inputType="text"
            />

        <EditText
            android:id="@+id/txtPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/senha"
            android:inputType="textPassword"
            />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/btnEntrar"
            android:background="@color/colorBtnLogin"
            android:textColor="@color/colorTxtLogin"
            android:textSize="17dp"
            android:padding="20dp"
            android:layout_marginTop="8dp"
            android:textStyle="bold"
            />
    </LinearLayout>
</ScrollView>

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

?>

php connection.

<?php
define('hostname', 'https://auth-db100.hostinger.com.br/index.php');
define('user', 'user');
define('password', 'password');
define('databaseName', 'datababase_mysql');
$connect = mysqli_connect(hostname, user, password, databaseName);
?>
  • already debugged the code to see where it goes? Maybe it goes through unsuccessful, maybe, in PHP, some of the tested variables are not set... To solve this, just debugging...

  • 1

    It seems that you are mixing mysqli with PDO, test your PHP code in a Postman or something, if it is working pass to android

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.