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 :

Code qui ne s'exécute plus


Sujet :

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 Code qui ne s'exécute plus
    Bonjour à tous

    Voici 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
    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
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
     
    package com.example.tourisme;
     
     
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import android.content.SharedPreferences;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    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.HttpGet;
    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 org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
     
    import com.example.a1.R;
     
     
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnCancelListener;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
     
     
     
    public class MainActivity extends Activity {
    	private Button connexion1;
    	private EditText username,password;
    	public ProgressDialog progressDialog;
    	public  String user,pass,givenUsername,givenPassword;
    	HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        List<NameValuePair> nameValuePairs;
     
     
     
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            connexion1 = (Button) findViewById(R.id.connexion);
            username = (EditText) findViewById(R.id.name);
            password = (EditText) findViewById(R.id.pass);
     
     
     
            		connexion1.setOnClickListener(new View.OnClickListener()
    		{
    			    public void onClick(View v)
    			{
     
    			    	connectWithHttpGet("USER","123");
     
    			}
     
    	    });
     
        }
     
     
     
     
     
     
     
     
        private void connectWithHttpGet(String givenUsername, String givenPassword) {
     
    		// Connect with a server is a time consuming process.
    		//Therefore we use AsyncTask to handle it
    		// From the three generic types;
    		//First type relate with the argument send in execute()
    		//Second type relate with onProgressUpdate method which I haven't use in this code
    		//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
    		class HttpGetAsyncTask extends AsyncTask<String, Void, String>{
     
    			@Override
    			protected String doInBackground(String... params) {
     
    				// As you can see, doInBackground has taken an Array of Strings as the argument
    				//We need to specifically get the givenUsername and givenPassword
    				String paramUsername = params[0];
    				String paramPassword = params[1];
    			//	showAlert("paramUsername is: " + paramUsername + " - paramPassword is :" + paramPassword);
     
    				// Create an intermediate to connect with the Internet
    				HttpClient httpClient = new DefaultHttpClient();
     
    				// Sending a GET request to the web page that we want
    				// Because of we are sending a GET request, we have to pass the values through the URL
    				HttpGet httpGet = new HttpGet("http://10.0.0.2/android_connect/c1.php?paramUsername=" + paramUsername + "&paramPassword=" + paramPassword);
    				String a="";
    				try {
    					// execute(); executes a request using the default context.
    					// Then we assign the execution result to HttpResponse
    					a="1";
    					HttpResponse httpResponse = httpClient.execute(httpGet);
    					//System.out.println("httpResponse");// getEntity()) ; obtains the message entity of this response
    					// getContent() ; creates a new InputStream object of the entity.
    					// Now we need a readable source to read the byte stream that comes as the httpResponse
    					InputStream inputStream = httpResponse.getEntity().getContent();
    a=a+"2";
    					// We have a byte stream. Next step is to convert it to a Character stream
    					InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    a=a+"3";
    					// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
    					BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    a=a+"4";
    					// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
    					//The buffer size is 8K
    					//Therefore we need a mechanism to append the separately coming chunks in to one String element
    					// We have to use a class that can handle modifiable sequence of characters for use in creating String
    					StringBuilder stringBuilder = new StringBuilder();
    					a=a+"5";
    					String bufferedStrChunk = null;
    					a=a+"6";
    					// There may be so many buffered chunks. We have to go through each and every chunk of characters
    					//and assign a each chunk to bufferedStrChunk String variable
    					//and append that value one by one to the stringBuilder
    					while((bufferedStrChunk = bufferedReader.readLine()) != null){
    						stringBuilder.append(bufferedStrChunk);
    						a=a+"7";
    					}
    					a=a+"8";
    					// Now we have the whole response as a String value.
    					//We return that value then the onPostExecute() can handle the content
    					showAlert("Returninge of doInBackground :" + stringBuilder.toString());
    					Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
    					// If the Username and Password match, it will return "working" as response
    					// If the Username or Password wrong, it will return "invalid" as response					
    					return stringBuilder.toString();
     
    				} catch (ClientProtocolException cpe) {
    					System.out.println("Exceptionrates caz of httpResponse :" + cpe);
    					cpe.printStackTrace();
    				} catch (IOException ioe) {
    					System.out.println("Secondption generates caz of httpResponse :" + ioe);
    					ioe.printStackTrace();
    				}
     
    				return null;
    			}
     
    			// Argument comes for this method according to the return type of the doInBackground() and
    			//it is the third generic type of the AsyncTask
    			@Override
    			protected void onPostExecute(String result) {
    				super.onPostExecute(result);
     
    				if(result.equals("working")){
    					showAlert("ok");
    					Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
    				}else{
    					Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
    				}				
    			}			
    		}
     
    		// Initialize the AsyncTask class
    		HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
    		// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
    		// We are passing the connectWithHttpGet() method arguments to that
    		httpGetAsyncTask.execute(givenUsername, givenPassword); 
     
    	}
         public void showAlert(final String h){
     		MainActivity.this.runOnUiThread(new Runnable() {
     		    public void run() {
     		    	AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
     		    	builder.setTitle("Login Error.");
     		    	builder.setMessage(h)  
     		    	       .setCancelable(false)
     		    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
     		    	           public void onClick(DialogInterface dialog, int id) {
     		    	           }
     		    	       });		    	       
     		    	AlertDialog alert = builder.create();
     		    	alert.show();		    	
     		    }
     		});
     	}
     
        }
    mon fichier php:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    <?php
     
    $varUsername = $_POST['paramUsername'];
    $varPassword = $_POST['paramPassword'];
     
    if($varUsername == "USER" && $varPassword == "123"){
    	echo 'working';
    }else{
    	echo 'invalid';
    }
     
    ?>
    mon fichier manifest
    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
     
    <?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" />
     
     
     
        <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>
     
     
        </application>
     
    </manifest>
    je veux tester par ce code que je peux communiquer entre mon fichier php et mon code JAVA

    quand je clique sur connexion

    j'ai remarqué que cette partie:
    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
     
    // execute(); executes a request using the default context.
    					// Then we assign the execution result to HttpResponse
    					a="1";
    					HttpResponse httpResponse = httpClient.execute(httpGet);
    					//System.out.println("httpResponse");// getEntity()) ; obtains the message entity of this response
    					// getContent() ; creates a new InputStream object of the entity.
    					// Now we need a readable source to read the byte stream that comes as the httpResponse
    					InputStream inputStream = httpResponse.getEntity().getContent();
    a=a+"2";
    					// We have a byte stream. Next step is to convert it to a Character stream
    					InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    a=a+"3";
    					// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
    					BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    a=a+"4";
    					// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
    					//The buffer size is 8K
    					//Therefore we need a mechanism to append the separately coming chunks in to one String element
    					// We have to use a class that can handle modifiable sequence of characters for use in creating String
    					StringBuilder stringBuilder = new StringBuilder();
    					a=a+"5";
    					String bufferedStrChunk = null;
    					a=a+"6";
    					// There may be so many buffered chunks. We have to go through each and every chunk of characters
    					//and assign a each chunk to bufferedStrChunk String variable
    					//and append that value one by one to the stringBuilder
    					while((bufferedStrChunk = bufferedReader.readLine()) != null){
    						stringBuilder.append(bufferedStrChunk);
    						a=a+"7";
    					}
    					a=a+"8";
    					// Now we have the whole response as a String value.
    					//We return that value then the onPostExecute() can handle the content
    					showAlert("Returninge of doInBackground :" + stringBuilder.toString());
    					Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
    					// If the Username and Password match, it will return "working" as response
    					// If the Username or Password wrong, it will return "invalid" as response					
    					return stringBuilder.toString();
    ne s'exécute plus

    j'ai vu côter fichier logcat >> il est vide >> aucune erreur

    SVP où est le problème??

  2. #2
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    Déjà toute la partie de récupération de String c'est plus simple de faire:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    String result = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
    Log.d("xxxxx","Received result: "+result);
    return result;
    Que par un périlleux code à base de InputStreamReader (qui ne prend au passage pas en compte le charset déclaré dans la réponse HTTP), BufferedReader et StringBuilder...
    (et préférer des Log.d(xxx) que des a=a+"5" ... )

    Ensuite "10.0.0.2" ne correspond à aucune adresse connue sur un téléphone (ou sur l'émulateur).

    En adresse approchante il y a bien "10.0.2.2" (qui est l'adresse de la machine hote qui fait tourner l'émulateur), donc uniquement disponible sur l'émulateur, et inutilisable sur un vrai device.

  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
    SVP je suis débutante je ne sais pas comment modifier mon code en utilisant ce que vous m'avez proposer

  4. #4
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    Bonjour
    voici mon nouveau 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
    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
    180
    181
    182
    183
     
    package com.example.tourisme;
     
     
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import android.content.SharedPreferences;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    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.HttpGet;
    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 org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
     
    import com.example.a1.R;
     
     
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnCancelListener;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
     
     
     
    public class MainActivity extends Activity {
    	private Button connexion1;
    	private EditText username,password;
    	public ProgressDialog progressDialog;
    	public  String user,pass,givenUsername,givenPassword;
    	HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        List<NameValuePair> nameValuePairs;
     
     
     
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            connexion1 = (Button) findViewById(R.id.connexion);
            username = (EditText) findViewById(R.id.name);
            password = (EditText) findViewById(R.id.pass);
     
     
     
            		connexion1.setOnClickListener(new View.OnClickListener()
    		{
    			    public void onClick(View v)
    			{
     
    			    	connectWithHttpGet("USER","123");
     
    			}
     
    	    });
     
        }
     
     
     
     
     
     
     
     
        private void connectWithHttpGet(String givenUsername, String givenPassword) {
     
    		// Connect with a server is a time consuming process.
    		//Therefore we use AsyncTask to handle it
    		// From the three generic types;
    		//First type relate with the argument send in execute()
    		//Second type relate with onProgressUpdate method which I haven't use in this code
    		//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
    		class HttpGetAsyncTask extends AsyncTask<String, Void, String>{
     
    			@Override
    			protected String doInBackground(String... params) {
     
    				// As you can see, doInBackground has taken an Array of Strings as the argument
    				//We need to specifically get the givenUsername and givenPassword
    				String paramUsername = params[0];
    				String paramPassword = params[1];
    			//	showAlert("paramUsername is: " + paramUsername + " - paramPassword is :" + paramPassword);
     
    				// Create an intermediate to connect with the Internet
    				HttpClient httpClient = new DefaultHttpClient();
     
    				// Sending a GET request to the web page that we want
    				// Because of we are sending a GET request, we have to pass the values through the URL
    				httpclient=new DefaultHttpClient();
    				httppost= new HttpPost("http://10.0.2.2/android_connect/c1.php");
    				try {
    					response=httpclient.execute(httppost);
    					String result = EntityUtils.toString(response.getEntity(),"UTF-8");
    					Log.d("xxxxx","Received result: "+result);
    					showAlert(result);
    					return result;
     
    				} catch (ClientProtocolException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
     
     
     
     
     
    				return null;
    			}
     
    			// Argument comes for this method according to the return type of the doInBackground() and
    			//it is the third generic type of the AsyncTask
    			@Override
    			protected void onPostExecute(String result) {
    				super.onPostExecute(result);
     
    				if(result.equals("working")){
    					showAlert("ok");
    					Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
    				}else{
    					Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
    				}				
    			}			
    		}
     
    		// Initialize the AsyncTask class
    		HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
    		// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
    		// We are passing the connectWithHttpGet() method arguments to that
    		httpGetAsyncTask.execute(givenUsername, givenPassword); 
     
    	}
         public void showAlert(final String h){
     		MainActivity.this.runOnUiThread(new Runnable() {
     		    public void run() {
     		    	AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
     		    	builder.setTitle("Login Error.");
     		    	builder.setMessage(h)  
     		    	       .setCancelable(false)
     		    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
     		    	           public void onClick(DialogInterface dialog, int id) {
     		    	           }
     		    	       });		    	       
     		    	AlertDialog alert = builder.create();
     		    	alert.show();		    	
     		    }
     		});
     	}
     
        }
    mais le résultat qui apparait dan alertShow est:
    Nom : Capture.PNG
Affichages : 260
Taille : 294,2 Ko

  5. #5
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    Le serveur web local n'a pas de page:
    "/android_connect/c1.php"

    Et renvoit donc un 404...

  6. #6
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    VOICI MON CODE PHP:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    <?php
     
    $varUsername = $_POST['paramUsername'];
    $varPassword = $_POST['paramPassword'];
     
    if($varUsername == "USER" && $varPassword == "123"){
    	echo 'working';
    }else{
    	echo 'invalid';
    }
     
    ?>
    et dans le page: http://127.0.0.1:8080/android_connect/c1.php

    j'aurai cette erreur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    Notice: Undefined index: paramUsername in C:\Program Files\EasyPHP-5.3.9\www\android_connect\c1.php on line 3
     
    Notice: Undefined index: paramPassword in C:\Program Files\EasyPHP-5.3.9\www\android_connect\c1.php on line 4
    invalid

  7. #7
    Membre émérite
    Avatar de LeBzul
    Homme Profil pro
    Inscrit en
    Décembre 2008
    Messages
    381
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations forums :
    Inscription : Décembre 2008
    Messages : 381
    Par défaut
    Salut,
    Si tu ne passes pas les données à ta requete http, forcement coté php il ne peut pas les avoir.
    Google te donnes toutes les réponses en cherchant un minimum :
    Lien google

  8. #8
    Membre Expert

    Homme Profil pro
    Consultant informatique
    Inscrit en
    Janvier 2004
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Janvier 2004
    Messages : 2 301
    Par défaut
    En php, il faut tester que le paramètre existe avant de l'utiliser... ou mettre '@' pour inhiber tous les message d'erreur (mais c'est moche...)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    <?php
     
    $varUsername = isset($_POST['paramUsername']) ? $_POST['paramUsername'] : null;
    $varPassword = isset($_POST['paramPassword']) ? $_POST['paramPassword'] : null;
     
    if($varUsername == "USER" && $varPassword == "123"){
    	echo 'working';
    }else{
    	echo 'invalid';
    }
    Cf. http://php.net/manual/fr/function.isset.php

  9. #9
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    merci à vous
    j'ai exécuté ce code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    <?php
     
    $varUsername = isset($_POST['paramUsername']) ? $_POST['paramUsername'] : 'USER';
    $varPassword = isset($_POST['paramPassword']) ? $_POST['paramPassword'] : '123';
     
    if($varUsername == "USER" && $varPassword == "123"){
    	echo 'working';
    }else{
    	echo 'invalid';
    }
    il m'a donné WORKING mais quand j'exécute ce 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
    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
    180
    181
    182
    183
     
    package com.example.tourisme;
     
     
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import android.content.SharedPreferences;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    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.HttpGet;
    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 org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
     
    import com.example.a1.R;
     
     
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnCancelListener;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
     
     
     
    public class MainActivity extends Activity {
    	private Button connexion1;
    	private EditText username,password;
    	public ProgressDialog progressDialog;
    	public  String user,pass,givenUsername,givenPassword;
    	HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        List<NameValuePair> nameValuePairs;
     
     
     
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            connexion1 = (Button) findViewById(R.id.connexion);
            username = (EditText) findViewById(R.id.name);
            password = (EditText) findViewById(R.id.pass);
     
     
     
            		connexion1.setOnClickListener(new View.OnClickListener()
    		{
    			    public void onClick(View v)
    			{
     
    			    	connectWithHttpGet("USER","123");
     
    			}
     
    	    });
     
        }
     
     
     
     
     
     
     
     
        private void connectWithHttpGet(String givenUsername, String givenPassword) {
     
    		// Connect with a server is a time consuming process.
    		//Therefore we use AsyncTask to handle it
    		// From the three generic types;
    		//First type relate with the argument send in execute()
    		//Second type relate with onProgressUpdate method which I haven't use in this code
    		//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
    		class HttpGetAsyncTask extends AsyncTask<String, Void, String>{
     
    			@Override
    			protected String doInBackground(String... params) {
     
    				// As you can see, doInBackground has taken an Array of Strings as the argument
    				//We need to specifically get the givenUsername and givenPassword
    				String paramUsername = params[0];
    				String paramPassword = params[1];
    			//	showAlert("paramUsername is: " + paramUsername + " - paramPassword is :" + paramPassword);
     
    				// Create an intermediate to connect with the Internet
    				HttpClient httpClient = new DefaultHttpClient();
     
    				// Sending a GET request to the web page that we want
    				// Because of we are sending a GET request, we have to pass the values through the URL
    				httpclient=new DefaultHttpClient();
    				httppost= new HttpPost("http://10.0.2.2/android_connect/c1.php");
    				try {
    					response=httpclient.execute(httppost);
    					String result = EntityUtils.toString(response.getEntity(),"UTF-8");
    					Log.d("xxxxx","Received result: "+result);
    					showAlert(result);
    					return result;
     
    				} catch (ClientProtocolException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
     
     
     
     
     
    				return null;
    			}
     
    			// Argument comes for this method according to the return type of the doInBackground() and
    			//it is the third generic type of the AsyncTask
    			@Override
    			protected void onPostExecute(String result) {
    				super.onPostExecute(result);
     
    				if(result.equals("working")){
    					showAlert("ok");
    					Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
    				}else{
    					Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
    				}				
    			}			
    		}
     
    		// Initialize the AsyncTask class
    		HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
    		// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
    		// We are passing the connectWithHttpGet() method arguments to that
    		httpGetAsyncTask.execute(givenUsername, givenPassword); 
     
    	}
         public void showAlert(final String h){
     		MainActivity.this.runOnUiThread(new Runnable() {
     		    public void run() {
     		    	AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
     		    	builder.setTitle("Login Error.");
     		    	builder.setMessage(h)  
     		    	       .setCancelable(false)
     		    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
     		    	           public void onClick(DialogInterface dialog, int id) {
     		    	           }
     		    	       });		    	       
     		    	AlertDialog alert = builder.create();
     		    	alert.show();		    	
     		    }
     		});
     	}
     
        }
    il me donne cette erreur
    Nom : Capture.PNG
Affichages : 227
Taille : 294,2 Ko

  10. #10
    Membre Expert

    Homme Profil pro
    Consultant informatique
    Inscrit en
    Janvier 2004
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Janvier 2004
    Messages : 2 301
    Par défaut
    l'url n'est pas bonne...

    tu es sûr de "http://10.0.2.2/android_connect/c1.php" ??

  11. #11
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    merci pour votre aide
    dans le browser quand je lance:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    http://127.0.0.1:8080/android_connect/c1.php
    il me donne WORKING

  12. #12
    Membre éprouvé
    Inscrit en
    Mars 2008
    Messages
    1 123
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1 123
    Par défaut
    voici mon projet en pièce jointe dans le lien ci-dessous:

    https://www.wetransfer.com/downloads...6135926/d605f7


    veuillez bien m'indiquer l'erreur
    sachant que je travail sur Eclipse JUNO M20130204-1200

  13. #13
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    Citation Envoyé par sky88 Voir le message
    merci pour votre aide
    dans le browser quand je lance:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    http://127.0.0.1:8080/android_connect/c1.php
    il me donne WORKING
    Donc depuis l'émulateur c'est:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    http://10.0.2.2:8080/android_connect/c1.php
    et pas
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    http://10.0.2.2/android_connect/c1.php

Discussions similaires

  1. Réponses: 2
    Dernier message: 06/05/2015, 16h20
  2. [Python 2.X] Code qui ne s'exécute qu'à la fermeture de la fenêtre root
    Par damiano84 dans le forum Tkinter
    Réponses: 3
    Dernier message: 21/10/2014, 07h21
  3. Grosse requête avec jointure qui ne s'exécute plus
    Par pitichamo dans le forum Requêtes
    Réponses: 5
    Dernier message: 22/11/2013, 16h45
  4. [AC-2007] Code qui ne s'exécute pas
    Par Triad30 dans le forum VBA Access
    Réponses: 4
    Dernier message: 22/07/2010, 19h42
  5. Réponses: 3
    Dernier message: 22/07/2005, 15h16

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