Login et password ,formulaire d'authentification sous android avec mysql et json


Tutoriel avec code et explication dans cette vidéo : 






Supposant que nous avons une table "user" dans une base de données mysql et nous voulons créé un code android qui permet à l'utilisateur d'accéder à son compte à partir d'un formulaire d'authentification. 

Table structure for table `user`

--
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nom` varchar(15) ,
  `prenom` varchar(15) ,
  `mail` varchar(100) ,
  `pass` varchar(100) ,
  PRIMARY KEY (`id`));

Nous devons par la suite hébergé un web services RESTful dans un serveur web apache. On suppose que nous avons créé un fichier db_connect.php qui contient les paramètres de connexion à la base .

db_connect.php

<?php
$connection=mysqli_connect("localhost","root","");
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$db_select = mysqli_select_db($connection, "loginmanager");
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
?>

Fichier login.php

<?php

include("db_connect.php");

$response=array();

if( isset($_POST["mail"]) && isset($_POST["pass"]) )
{
$mail=$_POST["mail"];
$pass=$_POST["pass"];
$req=mysqli_query($connection," select * from user where mail='$mail' and pass='$pass'  ");
if(mysqli_num_rows($req) > 0)
{
$response["success"]=1;
$response["message"]="login done successfully";
echo json_encode($response);
}
else{
$response["success"]=0;
$response["message"]="no user with this email or password";
echo json_encode($response);
}
}
else
{
$response["success"]=0;
$response["message"]="required field is missing";
echo json_encode($response);
}

?>

Nous devons par la suite créer notre interface graphique en XML :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/mail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="mail"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login" />
</LinearLayout>


Nous devons   implémenter maintenant notre code java, tout d'abord il faut ajouter la permission Internet dans le fichier manifest de notre projet : 
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>

  Dans les propriétés de la balise dans le manifest il faut ajouter la propriété suivante : android:usesCleartextTraffic="true" 
 
 ça doit etre comme ça :

<application

android:usesCleartextTraffic="true"
... >

Il faut aussi une classe JSONParser.java

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        conn.disconnect();

     // try parse the string to a JSON object
 try {
   jObj = new JSONObject(result.toString());
  } catch (JSONException e) {
   Log.e("JSON Parser", "Error parsing data " + e.toString());
 }

// return JSON Object
 return jObj;
    }
}
   

L'activité d'authentification :


import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    EditText mail,pass;
    Button b;
    ProgressDialog dialog;
JSONParser parser=new JSONParser();

int success;

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

        mail=findViewById(R.id.mail);
        pass=findViewById(R.id.pass);
        b=findViewById(R.id.login);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               new Log().execute();
            }
        });


    }

    class Log extends AsyncTask
    {

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

            dialog=new ProgressDialog(MainActivity.this);
            dialog.setMessage("Patientez SVP");
            dialog.show();

        }

        @Override
        protected String doInBackground(String... strings) {

            HashMap map=new HashMap<>();

            map.put("mail",mail.getText().toString());
            map.put("pass",pass.getText().toString());

            JSONObject object=parser.makeHttpRequest("http://10.0.2.2/login/login.php","POST",map);

            try {
                success = object.getInt("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }


            return null;
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            dialog.cancel();

            if(success==1)
            {
                AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
                alert.setMessage("Login done successfully");
                alert.setNeutralButton("ok",null);
                alert.show();
            }
            else
            {

                AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
                alert.setMessage("No user with this email or password");
                alert.setNeutralButton("ok",null);
                alert.show();
            }

        }
    }

}

   

Commentaires

  1. C'est fonctionnel,trés utile,merci bien.un bon travail.

    RépondreSupprimer
  2. c'est super pour sur l'émulateur de android studio mais si on utilise un téléphone pour nos test l'ip 10.0.2.2 n'est plus fonctionnel alors que mettre ?

    RépondreSupprimer
    Réponses
    1. Il faut mettre l'adresse IP de ta machine, il faut s'assurer aussi que ton logiciel qui contient le serveur web apache supporte le remote access, si c'est XAMPP donc tout ira bien, si c'est WAMP il y a une certaine configuration à faire pour permettre ceci.

      Supprimer
  3. j'ai cette erreur quand je saisis le mail et le password puis l'application se plainte et se ferme de lui meme

    voila l'erreur....
    {E/JSON Parser: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: ne.booba.dgiresencementmobile, PID: 8108
    java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:354)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
    at java.util.concurrent.FutureTask.run(FutureTask.java:271)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
    at ne.booba.dgiresencementmobile.Connexion$Log.doInBackground(Connexion.java:64)
    at ne.booba.dgiresencementmobile.Connexion$Log.doInBackground(Connexion.java:51)
    at android.os.AsyncTask$2.call(AsyncTask.java:333)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
    at java.lang.Thread.run(Thread.java:764) 
    }
    aidez moi a voir ou se trouve l'erreur

    RépondreSupprimer
    Réponses
    1. cela veut dire que le code java (partie mobile) n'est pas entrain de récupérer le résultat JSON fournit par le web service. Vérifie si ton adresse http de web service est saisie correctement ou vérifie si ton serveur apache est bien démarré ou non.

      Supprimer
  4. j'utilise xamp et le service apache est bien demare
    j'ai mis l'adresse ip de l'ordinateur : "http://192.168.43.64/Android/login.php" comme je test l'application sur un telephone android

    RépondreSupprimer
    Réponses
    1. Vérifie si la permission internet est bien ajouté dans le manifest. Sinon essaye d'accéder à l'url http://192.168.43.64/Android/login.php à partir du navigateur de ton téléphone, si le résultat JSON s'affiche alors le remote access s'effectue et tu as une erreur dans ton code. Dans le cas contraire, cela signifie que le pare feu bloque l'accès.

      Supprimer
  5. j'ai le doInBackground() et onPostExecute et le onPreExecute() qui sont barre dans mon code de android studio

    RépondreSupprimer
    Réponses
    1. Barré veut dire deprecated , celà n'affecte pas l'exécution

      Supprimer

Enregistrer un commentaire

Your comment will be reviewed by moderators

Posts les plus consultés de ce blog

Ionic 2 : Envoie d'une image vers un serveur web à l'aide de PHP et Angular 2

Premier tutoriel avec Arduino et Proteus ISIS