Android:为什么我的字符串变量在我的try-catch块之外无法识别?

时间:2017-06-14 22:00:49

标签: android try-catch

当我使用下面的代码在Logcat中打印getCategory时,我得到the category is Plumber(或者设置为review.setCategory的任何内容。)

  //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.
                            }

                        }

但是当我将System.out.println("the category is " + getCategory);放在活动中的任何其他地方时,在try-catch之外,我得到the category is null

我在Stackoverflow上阅读了很多帖子,通过在getCategory = null;块之前声明try-catch来解决这个问题但是并没有解决它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要指定name

的类型 在下面的示例中,您可以访问try

内设置的String name = ""; try{ name = "asdasd"; }catch (Exception e){ } System.out.println(name);
ListSelectionModel