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

API standards et tierces Android Discussion :

[Web Service] Problème requête HttpClient


Sujet :

API standards et tierces Android

  1. #1
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut [Web Service] Problème requête HttpClient
    salut
    en suivant un tutoriel sur le web service avec android (php et mysql). j'ai fais face à un problème: j'arrive à afficher la liste des produits ainsi qu'ajouter des produits (càd l'accès au serveur de base de données s'effectue avec succès) cependant lorsque je veux consulter les détails d'un produits j'ai une erreur dans LogCat que je ne comprends pas.
    voilà le code .java de la classe qui affiche les détails:
    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
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    public class EditProductActivity extends Activity {
     
        EditText txtName;
        EditText txtPrice;
        EditText txtDesc;
        EditText txtCreatedAt;
        Button btnSave;
        Button btnDelete;
     
        String pid;
     
        // Progress Dialog
        private ProgressDialog pDialog;
     
        // JSON parser class
        JSONParser jsonParser = new JSONParser();
     
        // single product url
        private static final String url_product_details = "http://monsite.com/get_product_details.php";
     
        // url to update product
        private static final String url_update_product = "http://android.com/update_product.php";
     
        // url to delete product
        private static final String url_delete_product = "http://android.com/delete_product.php";
     
        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_PRODUCT = "product";
        private static final String TAG_PID = "pid";
        private static final String TAG_NAME = "name";
        private static final String TAG_PRICE = "price";
        private static final String TAG_DESCRIPTION = "description";
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.edit_product);
     
            // save button
            btnSave = (Button) findViewById(R.id.btnSave);
            btnDelete = (Button) findViewById(R.id.btnDelete);
     
            // getting product details from intent
            Intent i = getIntent();
     
            // getting product id (pid) from intent
            pid = i.getStringExtra(TAG_PID);
     
            // Getting complete product details in background thread
            new GetProductDetails().execute();
     
            // save button click event
            btnSave.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // starting background task to update product
                    new SaveProductDetails().execute();
                }
            });
     
            // Delete button click event
            btnDelete.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // deleting product in background thread
                    new DeleteProduct().execute();
                }
            });
     
        }
     
        /**
         * Background Async Task to Get complete product details
         * */
        class GetProductDetails extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Loading product details. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Getting product details in background thread
             * */
            protected String doInBackground(String... params) {
     
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        // Check for success tag
                        int success;
                        try {
                            // Building Parameters
                            List<NameValuePair> params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair("pid", pid));
     
                            // getting product details by making HTTP request
                            // Note that product details url will use GET request
                            JSONObject json = jsonParser.makeHttpRequest(
                                    url_product_details, "GET", params);
     
                            // check your log for json response
                            Log.d("Single Product Details", json.toString());
     
                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                // successfully received product details
                                JSONArray productObj = json
                                        .getJSONArray(TAG_PRODUCT); // JSON Array
     
                                // get first product object from JSON Array
                                JSONObject product = productObj.getJSONObject(0);
     
                                // product with this pid found
                                // Edit Text
                                txtName = (EditText) findViewById(R.id.inputName);
                                txtPrice = (EditText) findViewById(R.id.inputPrice);
                                txtDesc = (EditText) findViewById(R.id.inputDesc);
     
                                // display product data in EditText
                                txtName.setText(product.getString(TAG_NAME));
                                txtPrice.setText(product.getString(TAG_PRICE));
                                txtDesc.setText(product.getString(TAG_DESCRIPTION));
     
                            }else{
                                // product with pid not found
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once got all details
                pDialog.dismiss();
            }
        }
     
        /**
         * Background Async Task to  Save product Details
         * */
        class SaveProductDetails extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Saving product ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Saving product
             * */
            protected String doInBackground(String... args) {
     
                // getting updated data from EditTexts
                String name = txtName.getText().toString();
                String price = txtPrice.getText().toString();
                String description = txtDesc.getText().toString();
     
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair(TAG_PID, pid));
                params.add(new BasicNameValuePair(TAG_NAME, name));
                params.add(new BasicNameValuePair(TAG_PRICE, price));
                params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
     
                // sending modified data through http request
                // Notice that update product url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                        "POST", params);
     
                // check json success tag
                try {
                    int success = json.getInt(TAG_SUCCESS);
     
                    if (success == 1) {
                        // successfully updated
                        Intent i = getIntent();
                        // send result code 100 to notify about product update
                        setResult(100, i);
                        finish();
                    } else {
                        // failed to update product
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product uupdated
                pDialog.dismiss();
            }
        }
     
        /*****************************************************************
         * Background Async Task to Delete Product
         * */
        class DeleteProduct extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Deleting Product...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Deleting product
             * */
            protected String doInBackground(String... args) {
     
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("pid", pid));
     
                    // getting product details by making HTTP request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_delete_product, "POST", params);
     
                    // check your log for json response
                    Log.d("Delete Product", json.toString());
     
                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // product successfully deleted
                        // notify previous activity by sending code 100
                        Intent i = getIntent();
                        // send result code 100 to notify about product deletion
                        setResult(100, i);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product deleted
                pDialog.dismiss();
     
            }
     
        }
    }
    JSONParser.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
    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;
     
        }
    }
    code get_product_details.php
    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
    <?php
     
    /*
     * Following code will get single product details
     * A product is identified by product id (pid)
     */
     
    // array for JSON response
    $response = array();
      header('Content-Type: text/html; charset=UTF-8');
    try
    {
        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        $pdo_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
        $bdd = new PDO('mysql:host=localhost;dbname=test', 'xxxxx', 'xxxx', $pdo_options);
    }
    catch (PDOException $e)
    {
        die('Erreur : ' . $e->getMessage());
    }
     
     
     
    // check for post data
    if (isset($_GET["pid"])) {
        $pid = $_GET['pid'];
     
        // get a product from products table
        $result = $bdd->prepare("SELECT *FROM products WHERE pid = :pid");
    	$result->bindValue(':pid', $pid, PDO::PARAM_INT);
    	$result->execute;
    $products = $req->fetchAll(PDO::FETCH_ASSOC);  
    $total_products = count($products);
     
    // check for empty result
        // looping through all results
        // products node
        $response["products"] = array();
        $cpt = 0;
        foreach ($products as $product) {
     
            // temp user array
            // push single product into final response array
            array_push($response["products"], $product);
    		$cpt++;
        }
        // success
        $response["success"] = 1;
     
        // echoing JSON response
        echo json_encode($response);
    }
    ?>

    Le rapport LogCat est dans les images "capture" puis "capture1" ci-jointes.

    Pouvez vous m-aider? merci
    Images attachées Images attachées   
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  2. #2
    Membre confirmé
    Homme Profil pro
    Ed Nat
    Inscrit en
    Janvier 2013
    Messages
    325
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : Ed Nat
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Janvier 2013
    Messages : 325
    Points : 559
    Points
    559
    Par défaut
    Bonjour,
    L'erreur est une networkonmainthreadexception : autrement dit Tentative d'accès au réseau depuis le main Thread de l'activity.
    Ce que tu dois trouver étonnant, puisque tu as utilisé une AsyncTask, justement pour exécuter les opérations network en dehors de ce Thread...

    Mais l'utilisation de AsyncTask n'est pas correcte, pour GetProductDetails.
    Dans AsyncTask :
    la méthode doInBackground se charge de faire les trucs réseau qui pourraient être bloquants, et ne doit absolument pas faire des appels au Thread principal.

    Or, toi tu le fais dans les lignes :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
     txtName = (EditText) findViewById(R.id.inputName);
    ...
    Cette mise à jour de l'interface ne peut se faire que dans la méthode onPostExecute, qui, elle permet d'intervenir sur le thread princ (ya le droit, c'est fait pour)

    Et du coup, ton runOnUiThread ne sert à rien...

    Ca pourrait donner ça :
    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
     
    private int success;
    protected String doInBackground(String... params) {
    	try {
    		// Building Parameters
    		List<NameValuePair> params = new ArrayList<NameValuePair>();
    		params.add(new BasicNameValuePair("pid", pid));
    		// getting product details by making HTTP request
    		// Note that product details url will use GET request
    		JSONObject json = jsonParser.makeHttpRequest(url_product_details, "GET", params);
     
    		// check your log for json response
    		Log.d("Single Product Details", json.toString());
    		// json success tag
    		success = json.getInt(TAG_SUCCESS);
    	} catch (JSONException e) {
    		e.printStackTrace();
    	}
    }
     
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
    	// dismiss the dialog once got all details
    	pDialog.dismiss();
    	if (success == 1) {
    		// successfully received product details
    		JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
    		// get first product object from JSON Array
    		JSONObject product = productObj.getJSONObject(0);
    		// product with this pid found
    		// Edit Text
    		txtName = (EditText) findViewById(R.id.inputName);
    		txtPrice = (EditText) findViewById(R.id.inputPrice);
    		txtDesc = (EditText) findViewById(R.id.inputDesc);
     
    		// display product data in EditText
    		txtName.setText(product.getString(TAG_NAME));
    		txtPrice.setText(product.getString(TAG_PRICE));
    		txtDesc.setText(product.getString(TAG_DESCRIPTION));
    	}
    }

  3. #3
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    j'ai changé le traitement de la vue dans OnPostExecute() et malgré ça ça ne fonctionne pas:
    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
     class GetProductDetails extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Loading product details. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Getting product details in background thread
             * */
             protected String doInBackground(String... params) {
     
     
                        // Check for success tag
     
                        try {
                            // Building Parameters
                            List<NameValuePair> paramss = new ArrayList<NameValuePair>();
                            paramss.add(new BasicNameValuePair("pid", pid));
     
                            // getting product details by making HTTP request
                            // Note that product details url will use GET request
                            JSONObject json = jsonParser.makeHttpRequest(
                                    url_product_details, "GET", paramss);
     
                            // check your log for json response
                            Log.d("Single Product Details", json.toString());
     
                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
     
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
     
     
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once got all details
                if (success == 1) {
                    // successfully received product details
                   try {
    				productObj = json.getJSONArray(TAG_PRODUCT);
    				 // get first product object from JSON Array
                    JSONObject product = productObj.getJSONObject(0);
                    // product with this pid found
                    // Edit Text
                    txtName = (EditText) findViewById(R.id.inputName);
                    txtPrice = (EditText) findViewById(R.id.inputPrice);
                    txtDesc = (EditText) findViewById(R.id.inputDesc);
     
                    // display product data in EditText
                    txtName.setText(product.getString(TAG_NAME));
                    txtPrice.setText(product.getString(TAG_PRICE));
                    txtDesc.setText(product.getString(TAG_DESCRIPTION));
     
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}// JSON Array
     
     
     
     
                }else{
                    // product with pid not found
                }
                pDialog.dismiss();
            }
        }
    Images attachées Images attachées  
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  4. #4
    Membre confirmé
    Homme Profil pro
    Ed Nat
    Inscrit en
    Janvier 2013
    Messages
    325
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : Ed Nat
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Janvier 2013
    Messages : 325
    Points : 559
    Points
    559
    Par défaut
    Ce n'est plus la même erreur, on avance !
    Par contre, je ne peux pas trop faire la correspondance entre la ligne d'erreur signalée (157) et ton code qui est partiel...
    Quand tu ne postes pas l'intégralité de ton code, signale impérativement à quelle ligne correspond l'exception...

    Je peux juste te faire remarquer ce qui ressemble à une incohérence :

    dans ta page PHP, tu construis la réponse avec $response["products"], alors qu'ensuite, tu essayes de récupérer
    productObj = json.getJSONArray(TAG_PRODUCT);
    avec
    private static final String TAG_PRODUCT = "product";
    donc c'est product ou products ?
    A mon avis, si tu mets la même chose sur les 2, ça ira mieux

  5. #5
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    J'ai changé les deux à "products" et voilà maintenant j'ai d'autre erreurs
    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
    package com.example.connexionbdd;
     
    import java.util.ArrayList;
    import java.util.List;
     
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    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;
     
    public class EditProductActivity extends Activity {
     
        EditText txtName;
        EditText txtPrice;
        EditText txtDesc;
        EditText txtCreatedAt;
        Button btnSave;
        Button btnDelete;
     
        String pid;
     
        // Progress Dialog
        private ProgressDialog pDialog;
     
        // JSON parser class
        JSONParser jsonParser = new JSONParser();
        JSONObject json;
        JSONArray productObj;
        int success;
        // single product url
        private static final String url_product_details = "http://training-android";
     
        // url to update product
        private static final String url_update_product = "";
     
        // url to delete product
        private static final String url_delete_product = "";
     
        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_PRODUCT = "products";
        private static final String TAG_PID = "pid";
        private static final String TAG_NAME = "name";
        private static final String TAG_PRICE = "price";
        private static final String TAG_DESCRIPTION = "description";
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.edit_product);
     
            // save button
            btnSave = (Button) findViewById(R.id.btnSave);
            btnDelete = (Button) findViewById(R.id.btnDelete);
     
            // getting product details from intent
            Intent i = getIntent();
     
            // getting product id (pid) from intent
            pid = i.getStringExtra(TAG_PID);
     
            // Getting complete product details in background thread
            new GetProductDetails().execute();
     
            // save button click event
            btnSave.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // starting background task to update product
                    new SaveProductDetails().execute();
                }
            });
     
            // Delete button click event
            btnDelete.setOnClickListener(new View.OnClickListener() {
     
                @Override
                public void onClick(View arg0) {
                    // deleting product in background thread
                    new DeleteProduct().execute();
                }
            });
     
        }
     
        /**
         * Background Async Task to Get complete product details
         * */
        class GetProductDetails extends AsyncTask<String, String, String> {
     
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditProductActivity.this);
                pDialog.setMessage("Loading product details. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }
     
            /**
             * Getting product details in background thread
             * */
            protected String doInBackground(String... params) {
     
     
                        // Check for success tag
     
                        try {
                            // Building Parameters
                            List<NameValuePair> paramss = new ArrayList<NameValuePair>();
                            paramss.add(new BasicNameValuePair("pid", pid));
     
                            // getting product details by making HTTP request
                            // Note that product details url will use GET request
                            JSONObject json = jsonParser.makeHttpRequest(
                                    url_product_details, "GET", paramss);
     
                            // check your log for json response
                            Log.d("Single Product Details", json.toString());
     
                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
     
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
     
     
     
                return null;
            }
     
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once got all details
            	 pDialog.dismiss();
            	 runOnUiThread(new Runnable() {
            		 public void run(){
            	            if (success == 1) {
            	                // successfully received product details
            	               try {
            					productObj = json.getJSONArray(TAG_PRODUCT);
            					 // get first product object from JSON Array
            	                JSONObject product = productObj.getJSONObject(0);
            	                // product with this pid found
            	                // Edit Text
            	                txtName = (EditText) findViewById(R.id.inputName);
            	                txtPrice = (EditText) findViewById(R.id.inputPrice);
            	                txtDesc = (EditText) findViewById(R.id.inputDesc);
     
            	                // display product data in EditText
            	                txtName.setText(product.getString(TAG_NAME));
            	                txtPrice.setText(product.getString(TAG_PRICE));
            	                txtDesc.setText(product.getString(TAG_DESCRIPTION));
     
            				} catch (JSONException e) {
            					// TODO Auto-generated catch block
            					e.printStackTrace();
            				}// JSON Array
     
     
     
     
            	            }else{
            	                // product with pid not found
            	            }
     
            		 }
            	 });
     
     
            }
        }
    Merci pour votre aide
    Images attachées Images attachées  
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  6. #6
    Membre confirmé
    Homme Profil pro
    Ed Nat
    Inscrit en
    Janvier 2013
    Messages
    325
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : Ed Nat
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Janvier 2013
    Messages : 325
    Points : 559
    Points
    559
    Par défaut
    Normal,
    tu as redéclaré en local l'objet json :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    JSONObject json = jsonParser.makeHttpRequest(
                                    url_product_details, "GET", paramss);
    à la ligne 131 dans doInBackground

    Enlève cette redéclaration en mettant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    json = jsonParser.makeHttpRequest(
                                    url_product_details, "GET", paramss);

  7. #7
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    Bon maintenant ça m'affiche les EditText (c'est à dire la vue) mais normalement il y aura les informations du produit passé en paramètres à travers le "pid"
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  8. #8
    Membre confirmé
    Homme Profil pro
    Ed Nat
    Inscrit en
    Janvier 2013
    Messages
    325
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : Ed Nat
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Janvier 2013
    Messages : 325
    Points : 559
    Points
    559
    Par défaut
    Tu veux dire qu'il n'y a rien dans tes zones de texte ?

    Que donne l'affichage dans les logs de l'objet json ?
    Log.d("Single Product Details", json.toString());

  9. #9
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    ça retourne le contenu de tout les produits et non pas un seul (celui avec le pid) :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    02-10 01:28:42.530: D/Single Product Details(4013): {"success":1,"products":[{"created_at":"2013-01-31 07:48:40","pid":"1","updated_at":"0000-00-00 00:00:00","price":"15.20","description":"hgchfjgfgk","name":"test"},{"created_at":"2013-01-31 09:56:39","pid":"2","updated_at":"0000-00-00 00:00:00","price":"12.50","description":"eeeeeeee","name":"hello"},{"created_at":"2013-01-31 18:35:52","pid":"3","updated_at":"0000-00-00 00:00:00","price":"15.80","description":"hhjjkjhg","name":"toi"},{"created_at":"2013-02-02 04:53:55","pid":"4","updated_at":"0000-00-00 00:00:00","price":"12.80","description":"sdgjjkl","name":"hdsgk"}]}
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  10. #10
    Membre confirmé
    Homme Profil pro
    Ed Nat
    Inscrit en
    Janvier 2013
    Messages
    325
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : Ed Nat
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Janvier 2013
    Messages : 325
    Points : 559
    Points
    559
    Par défaut
    Va à l'adresse http://monsite.com/get_product_details.php?pid=1 dans un navigateur
    Tu as plusieurs produits en réponse ?

  11. #11
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    Citation Envoyé par kox2ee Voir le message
    Va à l'adresse http://monsite.com/get_product_details.php?pid=1 dans un navigateur
    Tu as plusieurs produits en réponse ?
    j'obtient: {"product":[],"success":1}
    produit vide donc le remplissage de $response['product'] n'a pas été fais correctement..je cherche l'erreur dans le code php alors?
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  12. #12
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    j'ai changé le code php avec plus de controle if else pour savoir ou réside le problème maintenant il est comme ça:
    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
    <?php
     
    /*
     * Following code will get single product details
     * A product is identified by product id (pid)
     */
     
    // array for JSON response
    $response = array();
      header('Content-Type: text/html; charset=UTF-8');
    try
    {
        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        $pdo_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
        $bdd = new PDO('mysql:host=mysql;dbname=a2014', 'a2014', '08', $pdo_options);
    }
    catch (PDOException $e)
    {
        die('Erreur : ' . $e->getMessage());
    }
     
     
     
    // check for post data
    if (isset($_GET["pid"])) {
        $pid = $_GET['pid'];
     
        // get a product from products table
        $result = $bdd->prepare('SELECT * FROM products WHERE pid = :pid');
    	$result->bindValue(':pid', $pid, PDO::PARAM_INT);
    	$result->execute;
     $products = $result->fetchAll(PDO::FETCH_ASSOC);  
    $total_products = count($products);
    if (!empty($result)){
    if($total_products > 0){
    // check for empty result
        // looping through all results
        // products node
        $response["product"] = array();
        $cpt = 0;
        foreach ($products as $product) {
     
            // temp user array
            // push single product into final response array
            array_push($response["product"], $product);
    		$cpt++;
        }
        // success
        $response["success"] = 1;
     
        // echoing JSON response
        echo json_encode($response);
    	}
    	else {
    	// no product found
                $response["success"] = 0;
                $response["message"] = "No product found";
     
                // echo no users JSON
                echo json_encode($response);
    	}
    	}
    	else {
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";
     
        // echoing JSON response
        echo json_encode($response);
    	}
    }
    ?>
    Le résultat est:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    {"success":0,"message":"No product found"}
    alors qu'il existe dans la base de données: un produit avec pid=1
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  13. #13
    Membre confirmé
    Homme Profil pro
    Ed Nat
    Inscrit en
    Janvier 2013
    Messages
    325
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : Ed Nat
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Janvier 2013
    Messages : 325
    Points : 559
    Points
    559
    Par défaut
    Bonjour,
    tu as bien passé get_product_details.php?pid=1

    et le produit pid=1 existe bien en base de données ?

    Sinon, oui ton code php est bizarre...
    tu mets :
    $result->execute;
    $products = $req->fetchAll(PDO::FETCH_ASSOC);
    Alors que ça devrait être :
    $result->execute;
    $products = $result->fetchAll(PDO::FETCH_ASSOC);
    Tu fais un foreach sur les résultats, alors qu'au mieux, tu n'as qu'un seul produit, puisque je suppose que pid est la clé primaire

  14. #14
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    Citation Envoyé par kox2ee Voir le message
    Bonjour,
    tu as bien passé get_product_details.php?pid=1

    et le produit pid=1 existe bien en base de données ?

    Sinon, oui ton code php est bizarre...
    tu mets :


    Alors que ça devrait être :


    Tu fais un foreach sur les résultats, alors qu'au mieux, tu n'as qu'un seul produit, puisque je suppose que pid est la clé primaire
    oui j'ai passé dans le lien le pid=1, pour le foreach je l'utilise parce que j'ai oublié comment travailler avec php au cas un seul résultat , je dois remplacer avec quoi?
    merci pour votre aide.
    pour la faute de $req et $result, c'est déja corrigé sinon je n'obtiendrai pas le résultat
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

  15. #15
    Membre confirmé
    Homme Profil pro
    Ed Nat
    Inscrit en
    Janvier 2013
    Messages
    325
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : Ed Nat
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Janvier 2013
    Messages : 325
    Points : 559
    Points
    559
    Par défaut
    avec un fetch
    if($products = $result->fetch(PDO::FETCH_ASSOC)){
    //Code pour 1 produit trouvé
    }

  16. #16
    Membre actif Avatar de janyoura
    Femme Profil pro
    étudiante ingénierie informatique
    Inscrit en
    Mars 2012
    Messages
    365
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : étudiante ingénierie informatique

    Informations forums :
    Inscription : Mars 2012
    Messages : 365
    Points : 279
    Points
    279
    Par défaut
    Merci j'ai corrigé et voilà j'ai obtenu la réponse correcte
    Je retourne tester l'application maintenant
    "Scientists dream about doing great things. Engineers do them.”

    La réussite après tant de travail est un sentiment à vivre

    Si ton message est résolu, il y a un bouton qui est fait pour ça :
    Il se trouve tout en bas de la conversation !

    N'oublie pas que si ce message t'as aidé, tu peux voter pour lui en utilisant

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

Discussions similaires

  1. [Amazon Web Service] Signature requête
    Par aurelienl dans le forum Bibliothèques et frameworks
    Réponses: 9
    Dernier message: 30/09/2009, 10h32
  2. Projet Web + .Net, Web services : problème d'arguments
    Par Freud44 dans le forum Général Dotnet
    Réponses: 1
    Dernier message: 19/08/2009, 10h03
  3. Web Service : problème de serialisation d'objets
    Par cfeltz dans le forum Silverlight
    Réponses: 2
    Dernier message: 25/05/2009, 15h10
  4. Réponses: 10
    Dernier message: 26/08/2008, 10h00
  5. Web Services - Problème de communication serveur/client
    Par vern's dans le forum Web & réseau
    Réponses: 9
    Dernier message: 27/08/2007, 10h06

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