OkHttp 异步调用返回 JsonArray Null



我在okHttpCallback函数中声明了一个全局JSONArray变量,但它返回null。我正在获取数据,但是返回时它是空

JSONArray jsonArray; //Global in class
public JSONArray getJsonString(String link){
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(response.isSuccessful()){
try {
jsonArray = new JSONArray(response.body().string());
}catch (JSONException e){
e.printStackTrace();
}
}else{
Log.d("ERROR", "onResponse: ERROR" + response.body().string());
}
}
});

return jsonArray; // Null Here
}

实际上网络调用发生在另一个线程中,而您在主线程中返回jsonArray。只有当你通过okhttp获得响应时,你才应该返回jsonArray。 您应该执行以下操作:-

public void getJsonResponse(String link){
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(response.isSuccessful()){
try {
jsonArray = new JSONArray(response.body().string());
getJsonString(jsonArray);
}catch (JSONException e){
e.printStackTrace();
}
}else{
Log.d("ERROR", "onResponse: ERROR" + response.body().string());
}
}
});

}
// somewhere in class 
public JSONArray getJsonString(JSONArray jsonArr)
{
return jsonArr;
}

最新更新