IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

Problème authentification avec base de données externe


Sujet :

Android

  1. #1
    Membre averti
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Points : 443
    Points
    443
    Par défaut Problème authentification avec base de données externe
    Bonsoir,

    Je suis entrain de tester une authentification avec base de données et j'ai réussi à faire rediriger l'utilisateur lorsque ses coordonnées existent dans la base et je sais pas comment lui afficher un message d'erreur si ses coordonnées sont fausses.J'ai essayé plein de truc mais ça marche pas.
    voila mon code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    package com.gestionemploye.ahmed.gestionemploye;
     
    import android.util.Log;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
     
    import java.io.IOException;
     
    /**
     * Created by tahseen0amin on 16/02/2014.
     */
    public class ApiConnector {
     
     
        //***********************************************************************************************************************************
        //Récupérer tous les employes
        public JSONArray loginCustomer(String email,String password)
        {
            // URL for getting all customers
     
     
            String url = "http://192.168.0.15/scriptgestionemploye/login.php?EXTRA_EMAILADRESS="+email+"&EXTRA_PASSWORD="+password;
     
            // Get HttpResponse Object from url.
            // Get HttpEntity from Http Response Object
     
            HttpEntity httpEntity = null;
     
            try
            {
     
                DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
                HttpGet httpGet = new HttpGet(url);
     
                HttpResponse httpResponse = httpClient.execute(httpGet);
     
                httpEntity = httpResponse.getEntity();
     
     
     
            } catch (ClientProtocolException e) {
     
                // Signals error in http protocol
                e.printStackTrace();
     
                //Log Errors Here
     
     
     
            } catch (IOException e) {
                e.printStackTrace();
            }
     
     
            // Convert HttpEntity into JSON Array
            JSONArray jsonArray = null;
     
            if (httpEntity != null) {
                try {
                    String entityResponse = EntityUtils.toString(httpEntity);
     
                    Log.e("Entity Response  : ", entityResponse);
     
                    jsonArray = new JSONArray(entityResponse);
     
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
     
            return jsonArray;
     
     
        }
     
        //***********************************************************************************************************************************
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    package com.gestionemploye.ahmed.gestionemploye;
     
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
     
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
     
    public class MainActivity extends Activity {
     
        final Context context = this;
     
        private Button buttonlogin;
        private EditText editTextlogin;
        private EditText editTextpassword;
        private boolean verficationemail;
        Intent intent;
     
     
     
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
     
     
            setContentView(R.layout.activity_main);
     
            editTextlogin = (EditText)findViewById(R.id.emailaddress);
            editTextpassword = (EditText)findViewById(R.id.password);
     
            buttonlogin = (Button) findViewById(R.id.buttonlogin);
     
            // Configurer le button login de l'authentification**************************************
            buttonlogin.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
     
     
                 if(editTextpassword.getText().toString().equals("") || editTextlogin.getText().toString().equals("")){
     
                     Toast.makeText(getApplicationContext(),
                             "You must enter the fields", Toast.LENGTH_LONG).show();
                 }else
     
                    if(editTextlogin.getText().length()>=1) {
     
                        verficationemail = isValidEmail(editTextlogin.getText().toString());
     
                        if (verficationemail == false) {
     
                            Toast.makeText(getApplicationContext(),
                                    "Invalid format for email address", Toast.LENGTH_LONG).show();
                        }else{
     
     
     
                            new loginCustomerTask().execute(new ApiConnector());
     
     
     
     
                        }
                    }
     
     
                }
     
     
            });
     
        }
        // **************************************************************************************
     
     
            //Verifier le format des email
            private boolean isValidEmail(String email) {
            String emailRegex ="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
            if(email.matches(emailRegex))
            {
                return true;
            }
            return false;
        }
        // **************************************************************************************
     
     
        private class loginCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
        {
            @Override
            protected JSONArray doInBackground(ApiConnector... params) {
     
                // it is executed on Background thread
     
                JSONArray jsonArray = null;
     
                try{
     
                    //Redirection vers une autre activité
                    intent = new Intent();
                    intent.setClass(context,MenuActivity.class);
                    intent.putExtra("EXTRA_EMAILADRESS",editTextlogin.getText().toString());
                    intent.putExtra("EXTRA_PASSWORD",editTextpassword.getText().toString());
                    jsonArray = params[0].loginCustomer(editTextlogin.getText().toString(), editTextpassword.getText().toString());
                    JSONObject customerDetail = jsonArray.getJSONObject(0);
     
                        startActivity(intent);
                        return jsonArray;
     
     
     
     
     
                }catch (Exception e){
                    e.printStackTrace();
                }
                return jsonArray;
            }
     
        }
     
     
    }
    et mon script php est :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <?php
     
    if((isset($_REQUEST['EXTRA_EMAILADRESS'])) and (isset ($_REQUEST['EXTRA_PASSWORD']))){
     
    $con = mysql_connect("localhost");
     
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("test", $con);
     
    $emailAdress = $_REQUEST['EXTRA_EMAILADRESS'];
    $password = $_REQUEST['EXTRA_PASSWORD'];
     
    $result = mysql_query("SELECT * FROM employe WHERE email='$emailAdress' and password='$password'") or die('erreur query');
     
     
    while($row = mysql_fetch_assoc($result))
      {
    	$output[]=$row;
      }
     
    print(json_encode($output));
     
    mysql_close($con);
    }else{
    $output = "not found";
    print(json_encode($output));
    }
     
     
    ?>
    Merci

  2. #2
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2013
    Messages
    273
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Octobre 2013
    Messages : 273
    Points : 150
    Points
    150
    Par défaut
    tu peux essayer de t'inspirer de ce code, il effectue une authentification assez complete

    http://microlabs.niloo.fr/?p=211

    n'hesite pas si tu a des questions

  3. #3
    Membre averti
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Points : 443
    Points
    443
    Par défaut
    Merci pour votre réponse, au fait j'ai changer mon script php en utilisant l'attribut success = 1 comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    <?php
     
    if((isset($_REQUEST['EXTRA_EMAILADRESS'])) and (isset ($_REQUEST['EXTRA_PASSWORD']))){
     
    $con = mysql_connect("localhost");
     
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("test", $con);
     
    $emailAdress = $_REQUEST['EXTRA_EMAILADRESS'];
    $password = $_REQUEST['EXTRA_PASSWORD'];
     
     
     
    $result = mysql_query("SELECT * FROM employe WHERE email='$emailAdress' and password='$password'") or die('erreur query');
    $no_of_rows = mysql_num_rows($result);
     
    if($no_of_rows > 0){
    while($row = mysql_fetch_assoc($result))
      {
    	$output[]=$row;
      }
    $output["success"] = 1;
    print(json_encode($output));
     
    mysql_close($con);
    }else{
    $output["success"] = 0;
    print(json_encode($output));
    }
    }else{
    $output = "not found";
    print(json_encode($output));
    }
     
     
    ?>
    et dans ma classe j'ai ajouté les lignes en rouges :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    package com.gestionemploye.ahmed.gestionemploye;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    
    public class MainActivity extends Activity {
    
        final Context context = this;
    
        private Button buttonlogin;
        private EditText editTextlogin;
        private EditText editTextpassword;
        private boolean verficationemail;
        Intent intent;
        private static String KEY_SUCCESS = "success";
    
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
    
            setContentView(R.layout.activity_main);
    
            editTextlogin = (EditText)findViewById(R.id.emailaddress);
            editTextpassword = (EditText)findViewById(R.id.password);
    
            buttonlogin = (Button) findViewById(R.id.buttonlogin);
    
            // Configurer le button login de l'authentification**************************************
            buttonlogin.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
    
    
                 if(editTextpassword.getText().toString().equals("") || editTextlogin.getText().toString().equals("")){
    
                     gererDialogue();
    
    
                 }else
    
                    if(editTextlogin.getText().length()>=1) {
    
                        verficationemail = isValidEmail(editTextlogin.getText().toString());
    
                        if (verficationemail == false) {
    
                            gererDialogue();
                        }else{
    
    
    
                            new loginCustomerTask().execute(new ApiConnector());
    
    
    
    
                        }
                    }
    
    
                }
    
    
            });
    
        }
        // **************************************************************************************
    
    
            //Verifier le format des email
            private boolean isValidEmail(String email) {
            String emailRegex ="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
            if(email.matches(emailRegex))
            {
                return true;
            }
            return false;
        }
    
            //Gérer les boites de dialogues
            public void gererDialogue(){
    
                final AlertDialog alertDialog = new AlertDialog.Builder(
                        MainActivity.this).create();
                // Setting Dialog Title
                alertDialog.setTitle("Error Message");
                // Setting Dialog Message
                alertDialog.setMessage("You must verify the data");
                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.ic_launcher);
                // Setting OK Button
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Write your code here to execute after dialog closed
                        alertDialog.cancel();
                    }
                });
                // Showing Alert Message
                alertDialog.show();
            }
        // **************************************************************************************
    
    
        private class loginCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
        {
            @Override
            protected JSONArray doInBackground(ApiConnector... params) {
    
                // it is executed on Background thread
    
                JSONArray jsonArray = null;
    
                try{
    
                    //Redirection vers une autre activité
                    intent = new Intent();
                    intent.setClass(context,MenuActivity.class);
                    intent.putExtra("EXTRA_EMAILADRESS",editTextlogin.getText().toString());
                    intent.putExtra("EXTRA_PASSWORD",editTextpassword.getText().toString());
                    jsonArray = params[0].loginCustomer(editTextlogin.getText().toString(), editTextpassword.getText().toString());
                    JSONObject customerDetail = jsonArray.getJSONObject(0);
    
    
                    String res = customerDetail.getString(KEY_SUCCESS);
                    Log.d("****************",res.toString());
                    if (Integer.parseInt(res) == 1){
    
                        startActivity(intent);
                        return jsonArray;
                    }else{
                        gererDialogue();
                    }
    
    
    
    
    
    
                }catch (Exception e){
                    e.printStackTrace();
                }
                return jsonArray;
            }
    
        }
    
    
    }
    Malheuresement lorsque je teste maintenant si le login et le password que j'entre existe dans la base, il ne fait pas la redirection ainsi que lorsque je tape quelque chose qui n'existent pas la boite de dialogue contenant le message d'erreur ne s'affiche pas.

    Alors que lorsque je reviens au premier code, en cas d'existence, je fais la redirection.

    Merci

  4. #4
    Membre averti
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Points : 443
    Points
    443
    Par défaut
    j'ai ajouté ce bout de code

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     Log.d("****************","fgggggggggg");
                    JSONObject customerDetail = jsonArray.getJSONObject(0);
                    Log.d("****************","tttttttt");
                    String res = customerDetail.getString(KEY_SUCCESS);
                    Log.d("****************",res.toString());
    lors de l'exécution, le programme m'affiche seulement fgggggggggg aprés il ne passe pas au prochain affichage. et je pense le problème au niveau de cette ligne et je sais pas pourquoi

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
      JSONObject customerDetail = jsonArray.getJSONObject(0);

Discussions similaires

  1. Application mobile avec base de données externe
    Par tsiboko dans le forum Android
    Réponses: 1
    Dernier message: 12/02/2015, 12h58
  2. Problème PieChart avec base de données
    Par btssouma dans le forum JSF
    Réponses: 1
    Dernier message: 23/08/2012, 22h19
  3. [VBA-E] macro avec base de données externe
    Par Djohn dans le forum Macros et VBA Excel
    Réponses: 3
    Dernier message: 28/02/2007, 14h12
  4. Réponses: 11
    Dernier message: 22/11/2006, 07h31
  5. [MySQL] Problème avec base de données
    Par ThAOTh dans le forum PHP & Base de données
    Réponses: 8
    Dernier message: 10/08/2006, 13h42

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo