如何访问try-catch中的变量?

时间:2012-05-31 02:21:58

标签: java android json

我正在做类似

的事情
JSONArray json = uf.getAllRows();
(int x = 0; x <= json.length(); x++) {
JSONObject jo = json.getJSONObject(x); //Eclipse is suggesting that use try-catch here.

String name = jo.getString("username");
mainll[x] = new LinearLayout(this);
mainll[x].setId(x);
mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,   LayoutParams.WRAP_CONTENT));
mainll[x].setGravity(Gravity.CENTER);
.
.
.
.
}

如果我使用try catch,则“jo”在以下行中无法识别:

String name = jo.getString("username");

任何人都可以告诉我如何解决这个问题?

5 个答案:

答案 0 :(得分:3)

这样做:

JSONObject jo;
try {
    jo = json.getJSONObject(x);
} catch (...) {
    jo = null; // or other error handling
}

答案 1 :(得分:3)

只需一个简单的解决方案,您可以在try..catch块之外声明您的变量,这样您就可以访问它。

例如,

String myVariable = "";

try
{
     .
     .
     .
     myVariable = "Some Assignment"; 
}
catch ( Exception e ) { }

答案 2 :(得分:1)

只需包装所有内容

try{
  JSONArray json = uf.getAllRows();
  (int x = 0; x <= json.length(); x++) {
  JSONObject jo = json.getJSONObject(x); //Eclipse is suggesting that use try-catch here.

  String name = jo.getString("username");
  mainll[x] = new LinearLayout(this);
  mainll[x].setId(x);
  mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
  mainll[x].setGravity(Gravity.CENTER);
}
catch(Exception e){}

答案 3 :(得分:1)

您必须在try/catch之外声明 jo 变量:

String name;
try{

String name = jo.getString("username");
mainll[x] = new LinearLayout(this);
mainll[x].setId(x);
mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,   LayoutParams.WRAP_CONTENT));
mainll[x].setGravity(Gravity.CENTER);
}
catch(Exception ex)
{
 ///
}

答案 4 :(得分:0)

JSONArray json = uf.getAllRows();
JSONObject jo = null;
String name = "";

(int x = 0; x <= json.length(); x++) {
   try{
     jo = json.getJSONObject(x); //Eclipse is suggesting that use try-catch here.
   }catch(Exception ex){}

   name = jo.getString("username");
   mainll[x] = new LinearLayout(this);
   mainll[x].setId(x);
   mainll[x].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
   mainll[x].setGravity(Gravity.CENTER);
}