Bonsoir à tous
j'ai du problème dans mon code suivant:

require 'conn.php';
//$username='nn';
//$pass='nn';
 $query = "SELECT * FROM users";// where user_name='$username' and password='$pass' ";
$final_data = array();   
if ($query_run = mysql_query($query))
    {
        $i=0;
        $id ;
        while($query_row = mysql_fetch_assoc($query_run))
        {
          $id =$query_row ['user_id'];
         $i++; 
        }
         if( $i==0)
        {
$data = array('state' => '0', 'id' => 'Noid');
print (json_encode($data));
       }
         else {
$data = array('state' => '1', 'id' => ''.$id);
print (json_encode($data));
}

    }else{
     echo mysql_error();
    } 
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 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.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.*******.DialogInterface;
import android.*******.DialogInterface.OnCancelListener;
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;

public class MainActivity extends Activity {
    private Button connexion1;
    private EditText username,password;
    public ProgressDialog progressDialog;
    public  String user,pass;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    ProgressDialog dialog = null;

    private static String url = "http://10.0.0.2/android_connect/check.php";
    String result = null;
    InputStream is = null;
    JSONObject json_data=null;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        set*******View(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)
            {

                    String aa="nn";
                    String aa2="nn";
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://192.168.36.201/android_connect/check.php?username="+aa+"&pass="+aa2+"");

             try {

             HttpResponse response = httpclient.execute(httppost);
             String jsonResult = inputStreamToString(response.getEntity().get*******()).toString();
             JSONObject object = new JSONObject(jsonResult);

             String name = object.getString("state");
                  String verion = object.getString("id");
                  //textView.setText(name + " - " + verion);
                  int chk=Integer.parseInt(name);
                  if(chk==1)
                  {
                      showAlert("you are login"+"success  login thank you.");

                  }
                  else
                  {showAlert("no login"+"error  login please check user name or password ");
                  }

             }
             catch (JSONException e) {
                 Log.e("maconnexion_internet","Erreur de récupération des données",e);
             }
             catch (ClientProtocolException e) {
                 Log.e("maconnexion_internet","Erreur de récupération des données",e);
             }
             catch (IOException e) {
                 Log.e("maconnexion_internet","Erreur de récupération des données",e);
             }

            }

        });

    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
         while ((rLine = rd.readLine()) != null) {
          answer.append(rLine);
           }
        }

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

    }

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

    } 

quand je clique sur le bouton connexion rien ne se passe
où est le problème

4 réponses


Bonjour lovely_ned
Depuis android 3.0 les appels réseau doivent se faire dans un thread distinct du de l'UI thread
Tu dois passer par un AsyncTask ou créer ton propre Thread

SVP est ce que vous pouvez m'aider avec un simple exemple je suis débutante dans ce domaine
et comment je peux savoir la version de mon android??

Pour la partie Php tu dois choisir une 'Method' pour envoyer tes paramètres GET ou POST
comme tu utilises HttpPost dans la partie Android, en php tu dois utiliser $_POST[' nn'] pour récupérer le username
d'autre part avec POST tu dois passer les arguments via des paires clé/valeur comme ceci

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", varUsername));
nameValuePairs.add(new BasicNameValuePair("pass", varPass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

du coup tu ne dois pas passer les paramètres dans l'url

HttpPost httppost = new HttpPost("http://192.168.36.201/android_connect/check.php");

Merci à vous je vais essayer espérant que je n'aurai plus de problème