2017-06-14 3 views
-1

Lorsque j'imprime getCategory en Logcat avec le code ci-dessous je reçois the category is Plumber (ou quoi que review.setCategory est réglé sur.)Android: pourquoi ma variable chaîne n'est pas reconnue en dehors de mon bloc try-catch?

//post the review that has been clicked in the ListView and send it to 
     // ContactView.php and from that get other review details 
     StringRequest stringRequest = new StringRequest(Request.Method.POST, ContactView_URL, 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         //hide the 'loading' box when the page loads 
         pDialog.dismiss(); 
         //toast the response of ContactView.php, which has been converted to a 
         //JSON array in the Php file with JSON encode 
         Toast.makeText(ContactView.this, response, Toast.LENGTH_LONG).show(); 
         for (int i = 0; i < response.length(); i++) { 
          getCategory = null; 
          try { 
           JSONArray responseObject = new JSONArray(response); 
           JSONObject obj = responseObject.getJSONObject(i); 
           Review review = new Review(); 
           review.setCategory(obj.getString("category")); 
           review.setName(obj.getString("name")); 
           review.setPhone(obj.getString("phone")); 
           review.setAddress(obj.getString("address")); 
           review.setComment(obj.getString("comment")); 
           //we are getting the review id so we can pull extra needed info, like Address etc 
           //review.setReviewid(obj.getString("reviewid")); 
           Toast.makeText(ContactView.this, review.getCategory(), Toast.LENGTH_SHORT).show(); 
           //reviewList.add(review); 

           getCategory = review.getCategory(); 
           System.out.println("the category is " + getCategory); 
          } catch (JSONException e) { 
           Log.e("MYAPP", "unexpected JSON exception", e); 
           // Do something to recover ... or kill the app. 
          } 

         } 

Mais quand je mets le System.out.println("the category is " + getCategory); nulle part ailleurs dans l'activité, en dehors du try-catch, je reçois the category is null

Je lis beaucoup de messages sur Stackoverflow pour résoudre ce problème en déclarant getCategory = null; avant le bloc try-catch mais je ne le résous pas. Toute aide serait appréciée.

Répondre

0

Vous devez affecter le type de getCategory

dans l'exemple ci-dessous, vous pouvez accéder name qui a été placé à l'intérieur de la try

String name = ""; 

try{ 

    name = "asdasd"; 

}catch (Exception e){ 

} 

System.out.println(name); 
+0

Il * est * paramètre 'getCategory'. Le problème est que le bloc 'try' peut' throw' avant que 'getCategory' ne soit défini. –

+0

@RobertHarvey Je suggérerais alors avant le try catch, au lieu de le mettre à null. Définir une catégorie par défaut – Tony

+0

@Derek Pouvez-vous expliquer ce que vous entendez par catégorie par défaut? – CHarris