我是安卓新手,这里是类 问题库返回从 API 收到的 json obj 列表 ArrayAsyncResponse 在只包含一个方法进程的接口中完成,我读到 http 请求是异步的但无法关联
问题是模型类 情况 1( 当不存在 ArrayAsyncResponse 接口并且我将列表返回到主活动并打印它时,它显示空列表,但是当我调用 callback.processComplete(( 然后返回列表然后打印时,它会显示数据 case2 (如果我在这个函数 callback.processComplete(( 中传递 null,那么再次返回的列表为空 所以基本上界面正在帮助我们
公共类 问题库 { ArrayList questionArrayList = new ArrayList<>((; 私有字符串网址 = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<Question> getQuestions(final AnswerListAsyncResponse callBack) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
url,
(JSONArray) null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Question question = new Question();
question.setAnswer(response.getJSONArray(i).get(0).toString());
question.setAnswerTrue(response.getJSONArray(i).getBoolean(1));
//Add question objects to list
questionArrayList.add(question);
//Log.d("Hello", "onResponse: " + question.getAnswer());
// Log.d("JSON", "onResponse: " + response.getJSONArray(i).get(0));
//Log.d("JSON2", "onResponse: " + response.getJSONArray(i).getBoolean(1));
} catch (JSONException e) {
e.printStackTrace();
}
}
if (null != callBack) callBack.processFinished(questionArrayList);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
public class MainActivity extends AppCompatActivity {
private QuestionBank questionBank;
List<Question> questionList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionBank=new QuestionBank();
questionList=questionBank.getQuestions(new AnswerListAsyncResponse() {
@Override
public void processFinished(ArrayList<Question> questionsArrayList) {//this function triggers when response is received from api
Log.d("inside", "processFinished: "+questionsArrayList);
}
});
Log.d("sync response", "questionLIst: "+questionList);
}
}
抱歉,我无法在评论中写下此内容,但我想我可以为您提供帮助。
我不太明白你的问题。 但我认为您需要在课堂活动中获取异步的监听器。
您可以使用 EventBus 执行此操作,如下所示: https://github.com/greenrobot/EventBus