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

API standards et tierces Android Discussion :

problème connexion avec base MYSQL


Sujet :

API standards et tierces Android

  1. #1
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut problème connexion avec base MYSQL
    Bonjour à tous

    je voulais faire une authentification dans une BDD MYSQL

    voici mes codes:

    MainActivity.jaba

    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
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
     
    package com.example.tourisme;
     
     
    import java.util.ArrayList;
    import java.util.List;
     
     
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import com.example.a1.R;
    import Tourisme.Dialogue;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
     
     
    public class MainActivity extends Activity {
    	private Button connexion1;
    	private EditText name1,pass1;
    	public ProgressDialog progressDialog;
    	public  String url,user,pass;
    	HttpPost httppost;
    	StringBuffer buffer;
    	HttpResponse response;
    	HttpClient httpclient;
    	List<NameValuePair> nameValuePairs;
    	ProgressDialog dialog = null;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            connexion1 = (Button) findViewById(R.id.connexion);
    		name1 = (EditText) findViewById(R.id.name);
    		pass1 = (EditText) findViewById(R.id.pass);
     
     
    		connexion1.setOnClickListener(new View.OnClickListener()
    		{
     
     
    			    public void onClick(View v)
    			{
    			    	//parseJSON()  ;
    			//startActivity(new Intent(MainActivity.this, ville.class)); //Aller à une autre activité
    					//WebView wb = (WebView) findViewById(R.id.webView1); // Créer une vue WEB
    					//wb.loadUrl("http://arabhardware.net/forum/");
     
     
    					AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
     
     
    					int usersize = name1.getText().length();
    					int passsize = pass1.getText().length();
    					if (usersize > 0 && passsize > 0)
    					{
    						progressDialog.show();
    						String user = name1.getText().toString();
    						String pass = pass1.getText().toString();
    						//doLogin(user, pass);
     
    						 new Thread(new Runnable() {
    							    public void run() {
    							    	login();					      
    							    }
    							  }).start();
    					}
    					else
    					{
    						new Dialogue(alertDialog,1,"User or Password is empty !!");
    						//startActivity(new Intent(MainActivity.this, A1.class));
    					}
     
     
     
     
     
     
     
    			}
     
    	    });
     
        }
     
     
       // @Override
        /*public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }*/
     
     
     
         void login(){
     		try{			
     
     			httpclient=new DefaultHttpClient();
     			httppost= new HttpPost("http://127.0.0.1:8080/android_connect/check.php"); // make sure the url is correct.
     			//add your data
     			nameValuePairs = new ArrayList<NameValuePair>(2);
     			// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
     			nameValuePairs.add(new BasicNameValuePair("username",name1.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
     			nameValuePairs.add(new BasicNameValuePair("password",pass1.getText().toString().trim())); 
     			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     			//Execute HTTP Post Request
     			response=httpclient.execute(httppost);
     			// edited by James from coderzheaven.. from here....
     			ResponseHandler<String> responseHandler = new BasicResponseHandler();
     			final String response = httpclient.execute(httppost, responseHandler);
     			System.out.println("Response : " + response); 
     			runOnUiThread(new Runnable() {
     			    public void run() {
     			    	name1.setText("Response from PHP : " + response);
     					dialog.dismiss();
     			    }
     			});
     
     			if(response.equalsIgnoreCase("User Found")){
     				runOnUiThread(new Runnable() {
     				    public void run() {
     				    	Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
     				    }
     				});
     
     				startActivity(new Intent(MainActivity.this, UserPage.class));
     			}else{
     				showAlert();				
     			}
     
     		}catch(Exception e){
     			dialog.dismiss();
     			System.out.println("Exception : " + e.getMessage());
     		}
     	}
     
         public void showAlert(){
     		MainActivity.this.runOnUiThread(new Runnable() {
     		    public void run() {
     		    	AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
     		    	builder.setTitle("Login Error.");
     		    	builder.setMessage("User not Found.")  
     		    	       .setCancelable(false)
     		    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
     		    	           public void onClick(DialogInterface dialog, int id) {
     		    	           }
     		    	       });		    	       
     		    	AlertDialog alert = builder.create();
     		    	alert.show();		    	
     		    }
     		});
     	}
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
    AndroidManifest.xml:
    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
     
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.a1"
        android:versionCode="1"
        android:versionName="1.0" >
     
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="21" />
     
     	<uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
     
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.example.tourisme.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
     
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name="com.example.tourisme.UserPage"/>
     
        </application>
     
    </manifest>
    ActivityMain.xml:
    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
     
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:windowSoftInputMode="stateVisible|adjustPan" >
     
      <EditText
             android:id="@+id/name"					android:inputType="text"			android:textSize="@dimen/text_size"
             android:layout_width="fill_parent"		android:layout_height="30dp"
             android:layout_marginTop="110dp"	
             android:layout_alignParentLeft="true" />
     
      <TextView
          android:id="@+id/name1"
          android:layout_width="fill_parent"
          android:layout_height="30dp"
          android:layout_alignParentLeft="true"
          android:layout_alignParentTop="true"
          android:layout_marginTop="80dp"
          android:gravity="center_vertical"
          android:padding="5dip"
          android:text="@string/name1"
          android:textAppearance="?android:attr/textAppearanceLarge"
          android:textSize="@dimen/text_size" />
     
       <TextView
          android:id="@+id/pass1"
          android:layout_width="fill_parent"
          android:layout_height="30dp"
          android:layout_alignParentLeft="true"
          android:layout_alignParentTop="true"
          android:layout_marginTop="140dp"
          android:gravity="center_vertical"
          android:padding="5dip"
          android:text="@string/pass1"
          android:textAppearance="?android:attr/textAppearanceLarge"
          android:textSize="@dimen/text_size" />
     
        <EditText
             android:id="@+id/pass"					android:inputType="textPassword"			android:textSize="@dimen/text_size"
             android:layout_width="fill_parent"		android:layout_height="30dp"
             android:layout_marginTop="170dp"	    android:layout_alignParentLeft="true" />
     
        <Button
            android:id="@+id/connexion"
            android:layout_width="fill_parent"
            android:layout_height="35dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="220dp"
            android:gravity="center_vertical|center_horizontal"
            android:padding="5dip"
            android:text="@string/connexion"  android:textSize="@dimen/text_size"  />
     
    </RelativeLayout>
    et voici mon fichier de connexion avec la base ( je l'ai créé dans un dossier dans www de EasyPHP)
    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
     
    <?php
    $hostname_localhost ="localhost";
    $database_localhost ="androidhive";
    $username_localhost ="root";
    $password_localhost ="";
    $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
    or
    trigger_error(mysql_error(),E_USER_ERROR);
     
    mysql_select_db($database_localhost, $localhost);
     
    $username = $_POST['username'];
    $password = $_POST['password'];
    $query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
    $query_exec = mysql_query($query_search) or die(mysql_error());
    $rows = mysql_num_rows($query_exec);
    //echo $rows;
     if($rows == 0) { 
     echo "No Such User Found"; 
     }
     else  {
    	echo "User Found"; 
    }
    ?>
    Mais j'ai toujours ce problème:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     The Application has stopped enexpectedly

  2. #2
    Membre expérimenté
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2013
    Messages
    149
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2013
    Messages : 149
    Par défaut
    L'erreur du logcat éventuellement ?

  3. #3
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    l'erreur vient de la fonction login()
    parce que quand je l'ai masquée tout marche bien

  4. #4
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Par défaut
    Si tu as un crash (ce qui est le cas), merci de fournir l'erreur afférente complète apparaissant dans le LogCat (et seulement celle-ci, pas le LogCat en entier) s'il te plaît.
    Les boules de cristal sont en rupture de stock
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  5. #5
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    SVP est ce que vous pouvez me dire où je peux trouver le fichier logcat

  6. #6
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Par défaut
    Si tu utilises Eclipse : http://vogella.developpez.com/tutori...gging-Android/
    Si tu utilises Android Studio : c'est dans la vue "Android" (raccourci "6" par défaut).
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

  7. #7
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    je pense que le problème vient du:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    httppost= new HttpPost("http://127.0.0.1:8080/android_connect/check.php"); // make sure the url is correct.
    voici mon code logcat:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    02-11 15:23:26.392: D/dalvikvm(280): GC_FOR_MALLOC freed 3162 objects / 172696 bytes in 67ms
    02-11 15:23:26.451: W/SingleClientConnManager(280): Invalid use of SingleClientConnManager: connection still allocated.
    02-11 15:23:26.451: W/SingleClientConnManager(280): Make sure to release the connection before allocating another one.
    02-11 15:23:26.471: W/dalvikvm(280): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
    02-11 15:23:26.471: E/AndroidRuntime(280): FATAL EXCEPTION: Thread-8
    02-11 15:23:26.471: E/AndroidRuntime(280): java.lang.NullPointerException
    02-11 15:23:26.471: E/AndroidRuntime(280): 	at com.example.tourisme.MainActivity.login(MainActivity.java:144)
    02-11 15:23:26.471: E/AndroidRuntime(280): 	at com.example.tourisme.MainActivity$1$1.run(MainActivity.java:76)
    02-11 15:23:26.471: E/AndroidRuntime(280): 	at java.lang.Thread.run(Thread.java:1096)
    02-11 15:23:26.752: W/IInputConnectionWrapper(280): showStatusIcon on inactive InputConnection

  8. #8
    Modérateur
    Avatar de Hizin
    Homme Profil pro
    Développeur mobile
    Inscrit en
    Février 2010
    Messages
    2 180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : Développeur mobile

    Informations forums :
    Inscription : Février 2010
    Messages : 2 180
    Par défaut
    L'erreur est la suivante :
    Java.lang.NullPointerException 02-11 15:23:26.471: E/AndroidRuntime(280): at com.example.tourisme.MainActivity.login(MainActivity.java:144)

    L'erreur NullPointerException survient dans la classe MainActivity se situant dans le package com.example.tourisme. L'erreur est dans l'exécution de la méthode login. Le problème est dans le fichier MainActivity.java à la ligne 144.

    Il semble y avoir un décalage entre le code fourni et la ligne indiquée, je ne peux donc pas aller plus loin.

    Une NPE indique que tu invoques une méthode sur un objet null (non-initialisé) ou que tu passes un objet null à une méthode ne supportant pas cette valeur en tant que paramètre.
    C'est Android, PAS Androïd, ou Androïde didiou !
    Le premier est un OS, le second est la mauvaise orthographe du troisième, un mot français désignant un robot à forme humaine.

    Membre du comité contre la phrase "ça marche PAS" en titre et/ou explication de problème.

    N'oubliez pas de consulter les FAQ Android et les cours et tutoriels Android

Discussions similaires

  1. Problème de connexion à la base MySql avec Hibernate
    Par aloublack dans le forum Hibernate
    Réponses: 0
    Dernier message: 14/10/2010, 18h58
  2. Problème de connexion avec base MySql
    Par sophiec dans le forum QlikView
    Réponses: 1
    Dernier message: 09/07/2009, 18h27
  3. [Ado+Oracle] Problème connexion avec la base oracle
    Par Bourak dans le forum Bases de données
    Réponses: 6
    Dernier message: 05/04/2007, 09h30
  4. [MySQL] Connexion à la base MySQL avec PHP
    Par randriamanana dans le forum PHP & Base de données
    Réponses: 10
    Dernier message: 05/01/2007, 12h06
  5. [VB6]Problème connexion avec une base ACCESS
    Par mcay dans le forum VB 6 et antérieur
    Réponses: 8
    Dernier message: 15/05/2006, 17h47

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