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 :

MySQL -> PHP -> JSON -> Android


Sujet :

Android

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    37
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Janvier 2011
    Messages : 37
    Points : 24
    Points
    24
    Par défaut MySQL -> PHP -> JSON -> Android
    Bonsoir,

    Voilà j'ai une base de données qui contient cette table (image attachée).

    J’ai ensuite créé ce script PHP qui permet d’interroger ma base de données.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?php require_once "connect.php"; ?>
    			<?php
    				mysql_connect ($host,$user,$pass);
    				mysql_select_db ($db);
    				mysql_query("set names utf8");
    				$sql = "SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'";
    				$result = mysql_query ($sql) or die(mysql_error());
    					while( $row = mysql_fetch_assoc ($result) ) {
    							print(json_encode($row));
    					}
    			mysql_close();
    			?>
    Ensuite via ce code JAVA:

    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
    package tarabbia.mySQL;
     
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    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 android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.LinearLayout;
    import android.widget.TextView;
     
     
    public class Mains extends Activity {
    /** Called when the activity is first created. */
     
       TextView txt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Create a crude view - this should really be set via the layout resources  
        // but since its an example saves declaring them in the XML.  
        LinearLayout rootLayout = new LinearLayout(getApplicationContext());  
        txt = new TextView(getApplicationContext());  
        rootLayout.addView(txt);  
        setContentView(rootLayout);  
     
        // Set the text and call the connect function.  
        txt.setText("Connecting..."); 
      //call the method to run the data retreival
        txt.setText(getServerData(KEY_121)); 
     
     
     
    }
    public static final String KEY_121 = "http://jonathantarabbia.cwebh.org/seance_09/index.php"; 
     
     
     
    private String getServerData(String returnString) {
     
       InputStream is = null;
     
       String result = "";
        //the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","2010"));
     
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_121);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
     
        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }
     
        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }
        //parse json data
        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","id: "+json_data.getInt("id")+
                                ", name: "+json_data.getString("name")+
                                ", sex: "+json_data.getInt("sex")+
                                ", birthyear: "+json_data.getInt("birthyear")
                        );
                        //Get an output to the screen
                        returnString += "\n\t" + jArray.getJSONObject(i); 
                }
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
        return returnString; 
    }    
     
    }
    je me connecte à ma page web via le protocole HTPP, puis je converti JSON pour les afficher dans le logcat sous le "tag".

    Après teste, depuis mon androphone (samsung galaxy s), il arrive à se connecter à la page PHP puis la page renvoie cela :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    {"id":"1","name":"john","sex":"0","birthyear":"20"}{"id":"2","name":"toto","sex":"0","birthyear":"10"}{"id":"20","name":"john","sex":"0","birthyear":"20"}
    Mais lors de l'affichage dans mon logcat il me met une erreur de parsing (image attachée).

    Source code : https://sites.google.com/site/jtarabbia/fichiers

    Merci

    John
    Images attachées Images attachées  

  2. #2
    Membre averti Avatar de _Xavier_
    Profil pro
    Inscrit en
    Mai 2009
    Messages
    311
    Détails du profil
    Informations personnelles :
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations forums :
    Inscription : Mai 2009
    Messages : 311
    Points : 390
    Points
    390
    Par défaut
    Si tu essayes ça ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    JSONArray names= new JSONObject(result).names();
    JSONArray jArray = json.toJSONArray(names);
    for(int i=0;i<jArray.length();i++){
    //..
    }

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    37
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Janvier 2011
    Messages : 37
    Points : 24
    Points
    24
    Par défaut
    Merci pour ta réponse mais j'ai résolu le problème avec cette fonction là:

    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
    package Tarabbia.Xamax;
     
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ArrayAdapter;
     
    public class MySQL extends ListActivity {
    	InputStream is;
    	ArrayList<String> results = new ArrayList<String>();
    	JSONObject json_data;
     
    	@Override
    	 public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
     
    	 }
    	public void getData() {
    		String result = "";
    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     
    			 try{
    				 HttpClient httpclient = new DefaultHttpClient();
    				 HttpPost httppost = new HttpPost("http://jonathantarabbia.cwebh.org/seance_09/index.php");
    				 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    				 HttpResponse response = httpclient.execute(httppost);
    				 HttpEntity entity = response.getEntity();
    				 is = entity.getContent();
    			 }catch(Exception e){
    				 Log.e("log_tag", "Erreur de connexion http "+e.toString());
    			 }
     
    			 try{
    			 	 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    			 	 StringBuilder sb = new StringBuilder();
    			 	 String line = null;
    			 	 while ((line = reader.readLine()) != null) {
    			 		 sb.append(line + "\n");
    				 } 
    			 	 is.close();
    			 	 result=sb.toString();
    			 	 }catch(Exception e){
    			 		 Log.e("log_tag", "Error converting result "+e.toString());
    			 	 }
    			 try{
    		 			 JSONArray jArray = new JSONArray(result);
     
    		 			 for(int i=0;i<jArray.length();i++){
    			 			 json_data = jArray.getJSONObject(i);
    			 			 results.add((String) json_data.get("id") + " "+ json_data.get("name")+ " " + json_data.get("sex")+ " " + json_data.get("birthyear"));
    			 			 fillList();
    		 			 } 
    		 		}catch(JSONException e){
    					 Log.e("log_tag", "Error parsing data "+e.toString());
    				 }
     
    	 }
     
    	public void fillList() {
    		this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
    	}
    }
    puis après:


  4. #4
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    40
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2011
    Messages : 40
    Points : 26
    Points
    26
    Par défaut
    Salut,

    saurais-tu nous faire part de ta resolution complète car je n'arrive pas a compiler ton projet et je ne comprend pas pourquoi? Merci!

    Voici le projet que j'ai fait mais il ne fonctionne toujours pas...
    Fichiers attachés Fichiers attachés

  5. #5
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    40
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2011
    Messages : 40
    Points : 26
    Points
    26
    Par défaut
    voici un projet qui fonctionne pour ceux qui ont suivis :-)
    Fichiers attachés Fichiers attachés

  6. #6
    Futur Membre du Club
    Profil pro
    Inscrit en
    Mars 2011
    Messages
    4
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2011
    Messages : 4
    Points : 5
    Points
    5
    Par défaut
    Citation Envoyé par clement88 Voir le message
    voici un projet qui fonctionne pour ceux qui ont suivis :-)
    il ny a qu'un fichier .project dedans peut tu reposter la source en entier ? merci

  7. #7
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    40
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Février 2011
    Messages : 40
    Points : 26
    Points
    26
    Par défaut
    re,

    voilà qui est mieux:
    Fichiers attachés Fichiers attachés

  8. #8
    Nouveau Candidat au Club
    Inscrit en
    Août 2010
    Messages
    1
    Détails du profil
    Informations forums :
    Inscription : Août 2010
    Messages : 1
    Points : 1
    Points
    1
    Par défaut
    Citation Envoyé par clement88 Voir le message
    re,

    voilà qui est mieux:

    Bonjour,

    J'ai télécharger votre projet mais sa marche pas

    voilà l'erreur : Your project contains error(s), please fix theme before running your application

    Merci de me répondre

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 8
    Dernier message: 17/06/2013, 11h12
  2. JSON, accent, mysql et php (webservice)
    Par lilsgabbg dans le forum Langage
    Réponses: 1
    Dernier message: 19/07/2012, 14h06
  3. Dynatree, JSON, MySQL et PHP
    Par hubchau dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 28/06/2012, 13h13
  4. PHP array to json to android Spinner
    Par monta007 dans le forum Composants graphiques
    Réponses: 2
    Dernier message: 20/04/2011, 11h13

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