我正在做类似
的事情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");
任何人都可以告诉我如何解决这个问题?
答案 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);
}