gpt4 book ai didi

android - JsonRequester 库从内部函数访问监听器

转载 作者:行者123 更新时间:2023-11-30 01:23:23 24 4
gpt4 key购买 nike

我正在玩 JsonRequester Library它使用 volley 从 URLS 获取 JSON 数据。

我的问题是,如何从 getJson 函数内部的 onResponse 监听器返回 JSONObject?

这是我的 JsonHelpers 类:

import android.content.Context;
import android.support.annotation.Nullable;

import com.alirezaafkar.json.requester.interfaces.Methods;
import com.alirezaafkar.json.requester.interfaces.Response;
import com.alirezaafkar.json.requester.requesters.JsonObjectRequester;
import com.alirezaafkar.json.requester.requesters.RequestBuilder;
import com.android.volley.VolleyError;
import org.json.JSONObject;

public class JSONHelper {

public static int USER_REQUEST = 0;

public JSONObject getJson(Context context, String url){

JsonObjectRequester mUserRequester;




JsonObjectListener objectListener = new JsonObjectListener();

mUserRequester = new RequestBuilder(context)
.requestCode(USER_REQUEST)
.showError(true)
.buildObjectRequester(objectListener);

mUserRequester.request(Methods.GET, url);


}

private class JsonObjectListener extends Response.SimpleObjectResponse {
@Override
public void onResponse(int requestCode, @Nullable JSONObject jsonObject) {

}

@Override
public void onErrorResponse(int requestCode, VolleyError volleyError, @Nullable JSONObject errorObject) {
//Error (Not server or network error)
}

@Override
public void onFinishResponse(int requestCode, VolleyError volleyError, String message) {
//Network or Server error
}

@Override
public void onRequestStart(int requestCode) {
//Show loading or disable button
}

@Override
public void onRequestFinish(int requestCode) {
//Hide loading or enable button
}
}

}

最佳答案

回调

public interface Callback {
public void onResponse(JsonObject jsonObject);
}

当您需要 JsonObject

时的类
getJson(this, url, new Callback(){
public void onResponse(JsonObject jsonObject){
// Do what you want here
}
});

GetJson

public void getJson(Context context, String url, Callback callBack){
JsonObjectRequester mUserRequester;
JsonObjectListener objectListener = new JsonObjectListener();

mUserRequester = new RequestBuilder(context)
.requestCode(USER_REQUEST)
.showError(true)
.buildObjectRequester(objectListener);

mUserRequester.request(Methods.GET, url);
}

JsonObjectListener

private class JsonObjectListener extends Response.SimpleObjectResponse {
private Callback callback;
public JsonObjectListener(Callback callBack){
this.callBack = callBack;
}

@Override
public void onResponse(int requestCode, @Nullable JSONObject jsonObject){
callback.onResponse(jsonObject);
}
}

它应该可以工作,告诉它是否解决了您的问题。

关于android - JsonRequester 库从内部函数访问监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36769702/

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