我正在使用 this库以便从服务器获取数据。数据在服务器中解码为 JSONObject
。我创建的方法将调用 url 并返回 mysql
表中的行数。
该方法有效,但是我无法从我的方法中正确返回值:
解析级别.java
static public int countLevels() {
final int[] count = {0};
AndroidNetworking.get("https://example.com/gameLevels.php?option=count")
.setPriority(Priority.LOW)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
// responce is {count:20}
try {
count[0] = response.getInt("count"); // this is getting the value of 20
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("responce_app", String.valueOf(count[0]));
}
@Override
public void onError(ANError error) {
// handle error
Log.d("responce_app", String.valueOf(error)); //Logs out 20
}
});
return count[0]; // return always 0
}
当我从我的 MainActivity
调用时
Log.d("responce_app", String.valueOf(ParseLevels.countLevels()));
该方法始终返回 0。
我知道返回是在获取 jsonObject
之前触发的,但是,我如何才能等待方法获取 jsonObject
并在返回值之后?
在 iOS 中我使用类似的东西:
static func getLevels(feedsArray: (levelsCount : [Int]) -> Void) {
}
如何将其转换为 Java?
最佳答案
How can I wait for the method to fetch the jsonObject and after return the value?
两种选择:
1.在onResponse
方法中编写代码,根据请求的结果执行。
2. 使用interface
创建事件监听器并在countLevels
方法调用类中实现它以在onResponse< 时执行代码块
方法执行完成
关于java - Android - 在继续方法之前等待 json 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475300/