Reputation: 65
I declared a global JSONArray variable to return in okHttpCallback function but it returns null. I am getting data,But while returning it is 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
}
Upvotes: 0
Views: 178
Reputation: 1126
Actually the network call is taking place in another thread and you are returning jsonArray
in main thread. You should return jsonArray only when you get response through okhttp.
You should do as follows :-
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;
}
Upvotes: 1