找不到符号变量 Android Studio
Cannot find symbol variable Android Studio
我正在解析来自 JSON url 的数据。
但是 JSON 对象有不同的键。
我想从每个 json 对象获取所有数据,当它没有那个键时我想给它一个默认消息。
这就是我要使用的:
if(myJSONObject.has("mykey")) { <- in this case "abv"
//it has it, do appropriate processing
}
我得到了这个变量
private static final String TAG_ABV = "abv";
我尝试这样做是为了检查 abv 键是否包含在 JSON 中,并在未包含时为字符串提供默认文本 "No value"。
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
if(c.has("abv")) {
String abv = c.getString(TAG_ABV);
} else {
String abv = "No value";
}
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ABV, abv);
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
但是我有这个错误:找不到符号变量abv
我猜 if 语句中的 abv 超出了范围。
您在 if/else 块内声明 abv
,这意味着它只能在该块内访问。当您稍后尝试使用它时(在 data.put(TAG_ABV, abv);
中,您创建的变量不再可访问 - 它超出范围。如果将 abv
的声明移动到 if/else 语句之前的行,这应该可以解决您的错误。
我正在解析来自 JSON url 的数据。 但是 JSON 对象有不同的键。 我想从每个 json 对象获取所有数据,当它没有那个键时我想给它一个默认消息。
这就是我要使用的:
if(myJSONObject.has("mykey")) { <- in this case "abv"
//it has it, do appropriate processing
}
我得到了这个变量
private static final String TAG_ABV = "abv";
我尝试这样做是为了检查 abv 键是否包含在 JSON 中,并在未包含时为字符串提供默认文本 "No value"。
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
if(c.has("abv")) {
String abv = c.getString(TAG_ABV);
} else {
String abv = "No value";
}
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ABV, abv);
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
但是我有这个错误:找不到符号变量abv 我猜 if 语句中的 abv 超出了范围。
您在 if/else 块内声明 abv
,这意味着它只能在该块内访问。当您稍后尝试使用它时(在 data.put(TAG_ABV, abv);
中,您创建的变量不再可访问 - 它超出范围。如果将 abv
的声明移动到 if/else 语句之前的行,这应该可以解决您的错误。