Partage
  • Partager sur Facebook
  • Partager sur Twitter

Problème de code JSON

    9 février 2015 à 17:27:37

    Bonjour,

    J'ai des problèmes avec mon programme. Il est supposé me montrer le contenu de ma base de données contenue en local sur PHPmyAdmin. Mais il (et donc mon appli) retourne un message : "erreur". Je ne sais pas d'où vient le problème j'ai cherché sur internet en vain.

    Je sais que je demande beaucoup car mon programme est long. Merci si vous prenez le temps de me répondre.

    Voici mon programme :

    package com.mysql.enisandroidclub;
        
        import java.util.ArrayList;
        import java.util.List;
        
        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;
        
        import android.app.Activity;
        import android.content.Intent;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;
        import android.widget.Toast;
        
        public class ListDataActivity extends Activity {
         CustomProgressDialog  progressDialog;
         String urlGet="http://192.168.1.28/application/affichage_bd.php";
         GetDataAsyncTask getData;
         String message;
         int success;
         ListView lv;
         List<String> myListofData ;
         ArrayAdapter arrayadp; 
         
         @Override
         protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_list_data);
          progressDialog = new CustomProgressDialog(this, R.drawable.loading_throbber);
          progressDialog.setCancelable(true);
          lv=(ListView)findViewById(R.id.listView1);
          myListofData = new ArrayList<String>();
          getData=new GetDataAsyncTask();
          getData.execute(); 
          lv.setOnItemClickListener(new OnItemClickListener() {         
           public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
           {
            // s= value of seleted row
            String s=(String) (lv.getItemAtPosition(arg2)); 
            // on each row , I have save all of data separted by '-' : col1-col2-col3-col4
            String[] patrs = s.split(" - ");
            //parts[0] contains value of col1 , parts [1] contains value of col2 of each row
            Intent intent = new Intent(ListDataActivity.this, EditSuppActivity.class);
            //send data to the next activity
            intent.putExtra("col1Value", patrs[0]);
            intent.putExtra("col2Value", patrs[1]);
            intent.putExtra("col3Value", patrs[2]);
            intent.putExtra("col4Value", patrs[3]);
            startActivityForResult(intent, 100);
            finish();
                              
           }                                                              
          });
         } 
    private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { Log.i("add", "onPreExecute"); super.onPreExecute(); progressDialog.show(); } @Override protected Void doInBackground(Void... params) { Log.i("add", " start doInBackground"); ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(urlGet, ServiceHandler.GET); Log.d("Response: ",jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // return value of success success=jsonObj.getInt("success"); Log.i("success", String.valueOf(success)); if (success==0) { // success=0 ==> there is a string = message message=jsonObj.getString("message"); Log.i("message", message); } else if (success==1) { // success=1 ==> there is an array of data = valeurs JSONArray dataValues = jsonObj.getJSONArray("valeurs"); // loop each row in the array for(int j=0;j<dataValues.length();j++) { JSONObject values = dataValues.getJSONObject(j); // return values of col1 in valCol1 String valCol1= values.getString("col1"); // return values of col2 in valCol2 String valCol2= values.getString("col2"); String valCol3= values.getString("col3"); String valCol4= values.getString("col4"); //add a string witch contains all of data getted from the response myListofData.add(valCol1+" - "+valCol2+" - "+valCol3+" - "+valCol4); Log.i("Row "+(j+1), valCol1+" - "+valCol2+" - "+valCol3+" - "+valCol4); } } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } Log.i("add", " end doInBackground"); return null; } @Override protected void onPostExecute(Void result) { Log.i("add", "onPostExecute"); super.onPostExecute(result); if (progressDialog.isShowing()) { progressDialog.dismiss(); } if(success==1) { Toast.makeText(getApplicationContext(), "Bien recues ", Toast.LENGTH_LONG).show(); // show the list view contains the data arrayadp=new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, myListofData); lv.setAdapter(arrayadp); } else { Toast.makeText(getApplicationContext(), "Erreurs", Toast.LENGTH_LONG).show(); } } } }

    ServiceHander :

      package com.mysql.enisandroidclub;
        
        import java.io.IOException;
        import java.io.UnsupportedEncodingException;
        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.entity.UrlEncodedFormEntity;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.client.utils.URLEncodedUtils;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.util.EntityUtils;
        
        public class ServiceHandler {
        
         static String response = null;
         public final static int GET = 1;
         public final static int POST = 2;
        
         public ServiceHandler() {
        
         }
         
          /*
          * Making service call
          * @url - url to make request
          * @method - http request method
          * */
         public String makeServiceCall(String url, int method) {
          return this.makeServiceCall(url, method, null);
         }
        
         /*
          * Making service call
          * @url - url to make request
          * @method - http request method
          * @params - http request params
          * */
         public String makeServiceCall(String url, int method,List<NameValuePair> params) {
          try {
           // http client
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpEntity httpEntity = null;
           HttpResponse httpResponse = null;
           
           // Checking http request method type
           if (method == POST) {
            
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            
            if (params != null) {
             httpPost.setEntity(new UrlEncodedFormEntity(params));
            }
        
            httpResponse = httpClient.execute(httpPost);
        
           } else if (method == GET) {
            // appending params to url
            if (params != null) {
             String paramString = URLEncodedUtils
               .format(params, "utf-8");
             url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);
        
            httpResponse = httpClient.execute(httpGet);
        
           }
           httpEntity = httpResponse.getEntity();
           response = EntityUtils.toString(httpEntity);
        
          } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
          } catch (ClientProtocolException e) {
           e.printStackTrace();
          } catch (IOException e) {
           e.printStackTrace();
          }
          
          return response;
        
         }
        }

    Mon logcat et donc les erreurs que mon programme m'affiche :

        02-07 16:23:55.661: W/EGL_emulation(2572): eglSurfaceAttrib not implemented
        02-07 16:23:55.661: W/OpenGLRenderer(2572): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5b08fa0, error=EGL_SUCCESS
        02-07 16:23:59.498: I/add(2572): onPreExecute
        02-07 16:23:59.502: I/add(2572):  start doInBackground
        02-07 16:23:59.529: D/Response:(2572): <br />
        02-07 16:23:59.529: D/Response:(2572): <font size='1'><table class='xdebug-error xe-deprecated' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
        02-07 16:23:59.529: D/Response:(2572): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in D:\wamp\www\application\connexion.php on line <i>12</i></th></tr>
        02-07 16:23:59.529: D/Response:(2572): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
        02-07 16:23:59.529: D/Response:(2572): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
        02-07 16:23:59.529: D/Response:(2572): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0000</td><td bgcolor='#eeeeec' align='right'>241672</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='D:\wamp\www\application\affichage_bd.php' bgcolor='#eeeeec'>..\affichage_bd.php<b>:</b>0</td></tr>
        02-07 16:23:59.529: D/Response:(2572): <tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0000</td><td bgcolor='#eeeeec' align='right'>250776</td><td bgcolor='#eeeeec'>CONNEXION_DB->__construct(  )</td><td title='D:\wamp\www\application\affichage_bd.php' bgcolor='#eeeeec'>..\affichage_bd.php<b>:</b>24</td></tr>
        02-07 16:23:59.529: D/Response:(2572): <tr><td bgcolor='#eeeeec' align='center'>3</td><td bgcolor='#eeeeec' align='center'>0.0000</td><td bgcolor='#eeeeec' align='right'>250832</td><td bgcolor='#eeeeec'>CONNEXION_DB->connection(  )</td><td title='D:\wamp\www\application\connexion.php' bgcolor='#eeeeec'>..\connexion.php<b>:</b>4</td></tr>
        02-07 16:23:59.529: D/Response:(2572): <tr><td bgcolor='#eeeeec' align='center'>4</td><td bgcolor='#eeeeec' align='center'>0.0000</td><td bgcolor='#eeeeec' align='right'>251120</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysql-connect' target='_new'>mysql_connect</a>
        02-07 16:23:59.529: D/Response:(2572): (  )</td><td title='D:\wamp\www\application\connexion.php' bgcolor='#eeeeec'>..\connexion.php<b>:</b>12</td></tr>
        02-07 16:23:59.529: D/Response:(2572): </table></font>
        02-07 16:23:59.529: D/Response:(2572): {"valeurs":[{"col1":"1","col2":"dza","col3":"dza","col4":"dza"}],"success":1}
        02-07 16:23:59.530: W/System.err(2572): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
        02-07 16:23:59.530: W/System.err(2572):  at org.json.JSON.typeMismatch(JSON.java:111)
        02-07 16:23:59.530: W/System.err(2572):  at org.json.JSONObject.<init>(JSONObject.java:160)
        02-07 16:23:59.530: W/System.err(2572):  at org.json.JSONObject.<init>(JSONObject.java:173)
        02-07 16:23:59.530: W/System.err(2572):  at com.mysql.enisandroidclub.ListDataActivity$GetDataAsyncTask.doInBackground(ListDataActivity.java:84)
        02-07 16:23:59.530: W/System.err(2572):  at com.mysql.enisandroidclub.ListDataActivity$GetDataAsyncTask.doInBackground(ListDataActivity.java:1)
        02-07 16:23:59.530: W/System.err(2572):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
        02-07 16:23:59.530: W/System.err(2572):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        02-07 16:23:59.530: W/System.err(2572):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        02-07 16:23:59.530: W/System.err(2572):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        02-07 16:23:59.530: W/System.err(2572):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        02-07 16:23:59.530: W/System.err(2572):  at java.lang.Thread.run(Thread.java:818)
        02-07 16:23:59.530: I/add(2572):  end doInBackground
        02-07 16:23:59.557: W/EGL_emulation(2572): eglSurfaceAttrib not implemented
        02-07 16:23:59.557: W/OpenGLRenderer(2572): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5dfe960, error=EGL_SUCCESS
        02-07 16:23:59.599: W/EGL_emulation(2572): eglSurfaceAttrib not implemented
        02-07 16:23:59.599: W/OpenGLRenderer(2572): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5dfe900, error=EGL_SUCCESS
        02-07 16:23:59.631: I/add(2572): onPostExecute
    

     
    Ici sont contenus mes programmes php qui appelle ma BDD phpMyAdmin et qui sont appellés dans mon programme eclipse :


    Affichage_bd.php :

    <?php
        
         
        /*
         * Following code will list all the data in the db
         */
        
        
         
        // array for JSON response
        
        $response = array();
        
        
         
        // include db connect class
        
        require_once(__DIR__ . '/connexion.php');
        
        
         
        // connecting to db
        
        $db = new CONNEXION_DB();
        
        
         
        // get all products from products table
        
        $result = mysql_query("SELECT * FROM tableexemple") or die(mysql_error());
         
        
        
        // check for empty result
        
        if (mysql_num_rows($result) > 0) 
            {
           
        
         // looping through all results
        
            $response["valeurs"] = array();
        
         
            while ($row = mysql_fetch_array($result)) {
        
        
                // temp user array
        
                $ligne = array();
        
                $ligne["col1"] = $row["col1"];
        
                $ligne["col2"] = $row["col2"];
        
                $ligne["col3"] = $row["col3"];
        
                $ligne["col4"] = $row["col4"];
        
        
               
         
        // push single row into final response array
        
                array_push($response["valeurs"], $ligne);
        
            }
           
        
            // success
            
            $response["success"] = 1;
        
        
         
            // echo in JSON response
        
            echo json_encode($response);
        
        } else {
            
        
        // no products found
        
            $response["success"] = 0;
        
            $response["message"] = "No data found";
        
        
         
            // echo no users JSON
        
            echo json_encode($response);
        
        }
        
        ?>

    connexion.php :

    <?php
        class CONNEXION_DB {
          function __construct() { 
                $this->connection(); // connexion à la base
            }
           function __destruct() {
                $this->fermer(); // fermer la connexion
        
           }
         function connection() {
                // connexion à la base 
                $connexion = mysql_connect("localhost", "root", "") or die(mysql_error());
                 // selection de la base
                $db = mysql_select_db("test") or die(mysql_error()) or die(mysql_error());
                return $connexion;
            }
          function fermer() {
               mysql_close(); //Fermer la connexion
            }
        }
        ?>


    J'ai ajouté un `Log.e("Content :", "JSON Object: "+jsonObj.toString());`  pour savoir ce que contenais mon JSON  :

      02-09 08:54:42.147: E/Content :(2918): {"valeurs":[{"col1":"1","col2":"sza","col3":"sza","col4":"sza"},{"col1":"2","col2":"sza","col3":"sza","col4":"sza"},{"col1":"3","col2":"gui","col3":"huio","col4":"hio"},{"col1":"4","col2":"dza","col3":"dza","col4":"dza"},{"col1":"5","col2":"dza","col3":"dza","col4":"dza"},{"col1":"6","col2":"dza","col3":"dza","col4":"dza"},{"col1":"7","col2":"dza","col3":"dza","col4":"dza"},{"col1":"8","col2":"fez","col3":"fez","col4":"fez"},{"col1":"9","col2":"fez","col3":"fez","col4":"fez"},{"col1":"10","col2":"dza","col3":"dza","col4":"dza"},{"col1":"11","col2":"dza","col3":"dza","col4":"dza"},{"col1":"12","col2":"dzadza","col3":"dza","col4":"ddzazadza"},{"col1":"13","col2":"dzadza","col3":"dza","col4":"ddzazadza"},{"col1":"14","col2":"dza","col3":"dza","col4":"dza"},{"col1":"15","col2":"dza","col3":"dza","col4":"dza"},{"col1":"16","col2":"dza","col3":"dza","col4":"dza"},{"col1":"17","col2":"dza","col3":"dza","col4":"dza"},
        {"col1":"18","col2":"dza","col3":"dza","col4":"dza"},{"col1":"19","col2":"dza","col3":"tfger","col4":"eaz"},{"col1":"20","col2":"dza","col3":"dza","col4":"dza"}],"success":1}

    Mon programme me dit que mon JSON ne peut pas être de type string mais je le déclare comme un array dans mes programme php.

    Voilà je ne comprends pas pourquoi mon programme bug.

    -
    Edité par Loïc91 9 février 2015 à 18:06:10

    • Partager sur Facebook
    • Partager sur Twitter
      9 février 2015 à 19:33:36

      Les étapes:

      tu regardes ton erreur, là où le programme fait référence à une de tes classes (si tu vois ton nom dans la ligne, tu sais que c'est ce genre de ligne), tu copies l'erreur dans google : "

      Value of type java.lang.String cannot be converted to JSONObject


      Tu tombes sur ça :

      http://stackoverflow.com/questions/10267910/jsonexception-value-of-type-java-lang-string-cannot-be-converted-to-jsonobject

      Et dans la doc de java, il y a bien "String" comme paramètre possible de JSONObject :

      http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(java.lang.String)

      Donc avec ça, tu essaies de voir pourquoi ton string jsonString n'est pas accepté. Regarde le lien de stackoverflow, il y a plusieurs réponses données.

      • Partager sur Facebook
      • Partager sur Twitter
        10 février 2015 à 15:37:55

        Tout d'abord merci pour ta réponse et le lien.

        J'ai essayé d'appliquer la méthode du substring de ton lien mais elle est éffective que si on a des caratères en début de chaine qui sont
        pas accepté par le JSON cequi n'est pas mon cas. J'ai alors regardé la méthode suivante :

        return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));


        mais cette fois-ci, elle permet s'afficher toute la chaine de
        caractères comprise entre les {}. Or ma chaîne de caractère contenue dans mon JSON possède plusieurs {} cela fait donc
        bugger mon programme.

        J'ai néanmoins utilisé

        Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+ jsonStr);

        pour pouvoir voir plus précisément ce que contenait mon JSON et je tombe sur ca :

        02-10 12:50:15.827: W/System.err(1454): {"valeurs":[{"col1":"1","col2":"sza","col3":"sza","col4":"sza"},{"col1":"2","col2":"sza","col3":"sza","col4":"sza"},{"col1":"3","col2":"gui","col3":"huio","col4":"hio"},{"col1":"4","col2":"dza","col3":"dza","col4":"dza"},{"col1":"5","col2":"dza","col3":"dza","col4":"dza"},{"col1":"6","col2":"dza","col3":"dza","col4":"dza"},{"col1":"7","col2":"dza","col3":"dza","col4":"dza"},{"col1":"8","col2":"fez","col3":"fez","col4":"fez"},{"col1":"9","col2":"fez","col3":"fez","col4":"fez"},{"col1":"10","col2":"dza","col3":"dza","col4":"dza"},{"col1":"11","col2":"dza","col3":"dza","col4":"dza"},{"col1":"12","col2":"dzadza","col3":"dza","col4":"ddzazadza"},{"col1":"13","col2":"dzadza","col3":"dza","col4":"ddzazadza"},{"col1":"14","col2":"dza","col3":"dza","col4":"dza"},{"col1":"15","col2":"dza","col3":"dza","col4":"dza"},{"col1":"16","col2":"dza","col3":"dza","col4":"dza"},{"col1":"17","col2":"dza","col3":"dza","col4":"dza"},{"col1":"18","col2":"dza","col3":"dza","col4":"dza"},{"col1":"19","col2":"dza","col3":"tfger","col4":"eaz"},{"col1":"20","col2":"dza","col3":"dza","col4":"dza"}],"success":1
        02-10 12:50:15.828: W/System.err(1454): 	at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
        02-10 12:50:15.829: W/System.err(1454): 	at org.json.JSONTokener.readObject(JSONTokener.java:379)
        02-10 12:50:15.829: W/System.err(1454): 	at org.json.JSONTokener.nextValue(JSONTokener.java:100)
        02-10 12:50:15.829: W/System.err(1454): 	at org.json.JSONObject.<init>(JSONObject.java:156)
        02-10 12:50:15.829: W/System.err(1454): 	at org.json.JSONObject.<init>(JSONObject.java:173)
        02-10 12:50:15.830: W/System.err(1454): 	at com.mysql.enisandroidclub.ListDataActivity$GetDataAsyncTask.doInBackground(ListDataActivity.java:85)
        02-10 12:50:15.830: W/System.err(1454): 	at com.mysql.enisandroidclub.ListDataActivity$GetDataAsyncTask.doInBackground(ListDataActivity.java:1)
        02-10 12:50:15.830: W/System.err(1454): 	at android.os.AsyncTask$2.call(AsyncTask.java:288)
        02-10 12:50:15.830: W/System.err(1454): 	at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        02-10 12:50:15.830: W/System.err(1454): 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        02-10 12:50:15.831: W/System.err(1454): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        02-10 12:50:15.831: W/System.err(1454): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        

        A la fin de la 1ere ligne je n'obtient pas mon accollade fermante "}". Ce qui me donne une SyntaxError juste après.

        Une idée pour récupérer mon "}"?

        Merci encore pour l'aide apportée :).

        • Partager sur Facebook
        • Partager sur Twitter
          10 février 2015 à 16:22:37

          Je ne peux pas t'aider davantage, mais essaie les autres solutions, sinon refait une recherche google "parse string with jsonobject java", par exemple :

          JSONParser parser =newJSONParser();JSONObject json =(JSONObject) parser.parse(stringToParse);

          http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java

          • Partager sur Facebook
          • Partager sur Twitter
            10 février 2015 à 17:40:05

            D'accord je vais essayer de trouver merci encore.

            • Partager sur Facebook
            • Partager sur Twitter
              2 septembre 2016 à 12:37:39

              Bonjour je demande si vous avez bien eu une solution car j'ai eu un problème similaire et merci
              • Partager sur Facebook
              • Partager sur Twitter

              Problème de code JSON

              × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
              × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
              • Editeur
              • Markdown