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 :

Problème JSONParser


Sujet :

Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Par défaut Problème JSONParser
    Bonsoir,

    Je suis entrain de développer un petit exemple sur l'ajout d'une nouvelle ligne employé dans la base de données pour cela j'ai fait ceci :
    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
    package com.gestionemploye.ahmed.gestionemploye;
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    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.json.JSONException;
    import org.json.JSONObject;
    import android.util.Log;
     
    /**
     * Created by Ahmed on 04/12/2014.
     */
    public class JSONParser {
     
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
     
        // constructor
        public JSONParser() {
     
        }
     
        // function get json from url
    // by making HTTP POST or GET mehtod
        public JSONObject makeHttpRequest(String url, String method,
                                          List<NameValuePair> params) {
     
            // Making HTTP request
            try {
     
                // check for request method
                if (method == "POST") {
                    // request method is POST
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
     
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
     
                } else if (method == "GET") {
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
     
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }
     
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     
            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();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
     
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
     
            // return JSON String
            return jObj;
     
        }
     
     
        public static JSONObject getjObj() {
            return jObj;
        }
     
        public static void setjObj(JSONObject jObj) {
            JSONParser.jObj = jObj;
        }
    }
    et ma classe est :
    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
    package com.gestionemploye.ahmed.gestionemploye;
     
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.View.OnClickListener;
    import java.util.ArrayList;
    import java.util.List;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
     
    /**
     * Created by Ahmed on 04/12/2014.
     */
    public class AddNewEmploye extends Activity implements OnClickListener{
     
     
     
        // Progress Dialog
        private ProgressDialog pDialog;
        JSONParser jsonParser = new JSONParser();
        private EditText txtnewidiom;
        private EditText txtmeaning;
        private Button btnsavenew;
        private int success;
        //to determine JSON signal insert success/fail
        // url to insert new idiom (change accordingly)
        private static String url_insert_new = "http://192.168.1.7/androidexemple/insertnew.php";
        // JSON Node names
        private static final String TAG_SUCCESS = "success";
     
        @Override public void onCreate(Bundle savedInstanceState) {
     
            super.onCreate(savedInstanceState);
     
            setContentView(R.layout.ajoutemploye);
     
            // Edit Text
            txtnewidiom = (EditText) findViewById(R.id.textnewidiom);
            txtmeaning = (EditText) findViewById(R.id.txtmeaning);
     
            // Save button
            btnsavenew = (Button) findViewById(R.id.btnsavenew);
     
            // button click event
            btnsavenew.setOnClickListener(this);
        }
     
        @Override public void onClick(View v) {
     
            if (v.getId()==R.id.btnsavenew){
            //call the InsertNewIdiom thread
            new InsertNewIdiom().execute();
     
                if (success==1){
     
                    Toast.makeText(getApplicationContext(), "New idiom saved...", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "New idiom FAILED to saved...", Toast.LENGTH_LONG).show();
                }
            }
        }
        /** * Background Async Task to Create new Idioms * */
     
        class InsertNewIdiom extends AsyncTask<String, String, String> {
     
        //capture values from EditText
            String entry = txtnewidiom.getText().toString();
            String meaning = txtmeaning.getText().toString();
     
            /** * Before starting background thread Show Progress Dialog * */
     
                @Override protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(AddNewEmploye.this);
                pDialog.setMessage("Saving the new IDIOM ("+entry+")...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /** * Inserting the new idiom * */
                protected String doInBackground(String... args) {
            // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("entry", entry));
                params.add(new BasicNameValuePair("meaning", meaning));
              // getting JSON Object // Note that create product url accepts GET method
                JSONObject json = jsonParser.makeHttpRequest(url_insert_new, "GET", params);
     
     
              // check log cat from response
                Log.d("Insert New Idiom Response", json.toString());
     
              // check for success tag
                    try {
                  success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                  // successfully save new idiom
                            } else {
                  // failed to add new idiom
                                }
                            } catch (JSONException e)
              {
                    e.printStackTrace();
              }
              //return null;
              return null; }
            /** * After completing background task Dismiss the progress dialog * **/
     
            protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
                 pDialog.dismiss();
            }
        }
    }
    et j'ai activé la permission android.permission.INTERNET

    En exécutant le code j'obtiens l 'erreur suivante :

    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
    691-705/com.gestionemploye.ahmed.gestionemploye E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
        java.lang.RuntimeException: An error occured while executing doInBackground()
                at android.os.AsyncTask$3.done(AsyncTask.java:278)
                at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
                at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
                at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                at java.lang.Thread.run(Thread.java:856)
         Caused by: java.lang.NullPointerException
                at com.gestionemploye.ahmed.gestionemploye.AddNewEmploye$InsertNewIdiom.doInBackground(AddNewEmploye.java:105)
                at com.gestionemploye.ahmed.gestionemploye.AddNewEmploye$InsertNewIdiom.doInBackground(AddNewEmploye.java:77)
                at android.os.AsyncTask$2.call(AsyncTask.java:264)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

    la ligne 105 dans l'erreur pointe sur cette ligne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
                JSONObject json = jsonParser.makeHttpRequest(url_insert_new, "GET", params);
    et la ligne 77 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    class InsertNewIdiom extends AsyncTask<String, String, String> {
    Merci pour votre aide !

  2. #2
    Membre expérimenté Avatar de Altak
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2014
    Messages
    170
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Octobre 2014
    Messages : 170
    Par défaut
    Bonjour,

    Lance l'application en debug et verifie que ton jsonParser est instancié, ainsi que tes variables params et url_insert_new.
    Vérifie aussi que ce que tu ajoute dans ta list params soit bien instancié.

    Tu as une NullpointerException donc ca vient forcement d'une erreur de ce type.

    glhf

  3. #3
    Membre éclairé
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Par défaut
    oui mon jsonparser est instancié
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
        JSONParser jsonParser = new JSONParser();
    par contre j'ai un souci sur le insertnew.pho j'ai mis ce fichier dans un fichier android exemple sous le www du wamp server. j’accède à ce serveur depuis mon pc avec 127.0.0.1.

    Est-ce-que l'adresse url est-elle-correcte?Sinon est-ce-que je dois ouvrir le wifi sur mon émulateur android ou un truc comme ça ?

  4. #4
    Membre éclairé
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations forums :
    Inscription : Mai 2011
    Messages : 790
    Par défaut
    euh la ligne 105 pointe sur cette erreur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
      Log.d("Insert New Idiom Response", json.toString());

  5. #5
    Membre expérimenté Avatar de Altak
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2014
    Messages
    170
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Octobre 2014
    Messages : 170
    Par défaut
    Re,

    Je vois que tu n'instancie ton retour que ici :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    L'exception sur le toString() laisse a penser qu'a cette ligne le JSONObject(json) fail et que ta variable n'est jamais initialisé.
    Affiche ta string pour voir si elle est correct.

    Sinon, pour l'url, cela me semble correct. As-tu essayé d'ajouter le port d’écoute de ton serveur apache? par exemple 192.168.1.7:80 ou 192.168.1.4:8080
    il est possible que le probleme vienne de la aussi (un long moment que j'ai pas fait de serveur apache ^^)

    Mais tu n'as pas d'autre message sur la console avant d'avoir ton plantage?
    Avec tes catch, tu devrais avoir des messages d'erreur bien avant que tu appel le toString().

    glhf

  6. #6
    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
    Et surtout remplace:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Log.e("JSON Parser", "Error parsing data " + e.toString());
    par
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Log.e("JSON Parser", "Error parsing data" ,e);

Discussions similaires

  1. Problème d'installation oracle 8.1.7 sous NT
    Par Anonymous dans le forum Installation
    Réponses: 7
    Dernier message: 02/08/2002, 14h18
  2. Problème d'impression
    Par IngBen dans le forum C++Builder
    Réponses: 7
    Dernier message: 22/05/2002, 11h37
  3. Problème avec la mémoire virtuelle
    Par Anonymous dans le forum CORBA
    Réponses: 13
    Dernier message: 16/04/2002, 16h10
  4. Réponses: 6
    Dernier message: 25/03/2002, 21h11

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