Java Android-等待json获取值,然后继续使用方法
我使用库从服务器获取数据。数据在服务器中解码为Java Android-等待json获取值,然后继续使用方法,java,android,mysql,json,Java,Android,Mysql,Json,我使用库从服务器获取数据。数据在服务器中解码为JSONObject。我创建的方法将调用url并返回mysql表中的行数 该方法正在工作,但是,我无法从我的方法正确返回值: ParseLevels.java static public int countLevels() { final int[] count = {0}; AndroidNetworking.get("https://example.com/gameLevels.php?option=count"
JSONObject
。我创建的方法将调用url并返回mysql
表中的行数
该方法正在工作,但是,我无法从我的方法正确返回值:
ParseLevels.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
}
当我从我的main活动中呼叫时
Log.d(“response_app”,String.valueOf(ParseLevels.countLevels())代码>
该方法始终返回0
我知道返回是在提取jsonObject
之前触发的,但是,如何等待方法提取jsonObject
并在返回值之后呢
在iOS中,我使用类似于:
static func getLevels(feedsArray: (levelsCount : [Int]) -> Void) {
}
如何将其转换为Java?您应该查看库自述文件中的生成同步请求的示例:
ANRequest=AndroidNetworking.get(“https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}”)
.addPathParameter(“页码”,“0”)
.addQueryParameter(“限制”、“3”)
.build();
ANResponse=request.executeForParsed(新类型令牌(){});
if(response.issucess()){
List users=responsewo.getResult();
}否则{
//处理错误
}
您将在response.issucess()
conditional中返回计数。您应该查看库自述文件中的发出同步请求的示例:
ANRequest=AndroidNetworking.get(“https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}”)
.addPathParameter(“页码”,“0”)
.addQueryParameter(“限制”、“3”)
.build();
ANResponse=request.executeForParsed(新类型令牌(){});
if(response.issucess()){
List users=responsewo.getResult();
}否则{
//处理错误
}
您将在response.issucess()
条件中返回您的计数
我如何等待该方法获取jsonObject并在返回后返回
价值呢
两种选择:
1.在onResponse
方法中执行代码,该方法要根据请求的结果执行
2.使用接口创建事件侦听器
并在countLevels
方法调用方类中实现它,以便在onResponse
方法执行完成时执行代码块
我如何等待该方法获取jsonObject并在返回后返回
价值呢
两种选择:
1.在onResponse
方法中执行代码,该方法要根据请求的结果执行
2.使用接口创建事件侦听器
并在countLevels
方法调用方类中实现它,以便在onResponse
方法执行完成时执行代码块我已经尝试过这个方法,但是,我得到错误无法解决方法'issucess()
但是我已经尝试过这个方法,我收到错误无法解决方法'issucess()
谢谢。我已经使用接口创建了事件侦听器:public interface CountLevelCallback{void afterCount(int count);}
谢谢。我使用以下接口创建了事件侦听器:public interface CountLevelCallback{void afterCount(int count);}
ANRequest request = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.build();
ANResponse<List<User>> response = request.executeForParsed(new TypeToken<List<User>>() {});
if (response.isSuccess()) {
List<User> users = responseTwo.getResult();
} else {
//handle error
}