0

我在做类似的事情

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");

谁能告诉我如何解决这个问题?

4

5 回答 5

3

像这样做:

JSONObject jo;
try {
    jo = json.getJSONObject(x);
} catch (...) {
    jo = null; // or other error handling
}
于 2012-05-31T02:25:56.803 回答
3

只是一个简单的解决方案,您可以在 try..catch 块之外声明您的变量,以便您能够访问它。

例如,

String myVariable = "";

try
{
     .
     .
     .
     myVariable = "Some Assignment"; 
}
catch ( Exception e ) { }
于 2012-05-31T02:26:03.237 回答
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){}
于 2012-05-31T02:26:03.153 回答
1

您必须在外部声明您的jo变量try/catch

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)
{
 ///
}
于 2012-05-31T02:29:25.450 回答
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);
}
于 2012-05-31T05:00:48.563 回答