gpt4 book ai didi

java - OkHttp 异步调用返回 JsonArray Null

转载 作者:行者123 更新时间:2023-12-02 09:25:13 25 4
gpt4 key购买 nike

我声明了一个全局 JSONArray 变量以在 okHttpCallback 函数中返回,但它返回 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;
}

关于java - OkHttp 异步调用返回 JsonArray Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58388096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com