java - 为什么即使我在请求期间向其中添加了元素,此代码也会显示一个空数组列表?
问题描述
我的代码是这样的,我不知道为什么它得到一个空数组,即使我在请求期间将元素添加到数组中。
公共类 MainActivity 扩展 AppCompatActivity {
private List<Question> questionList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionList = new QuestionBank().getQuestions();
Log.d("Main", "processFinished: " + questionList);
}
// 请求公共类 QuestionBank {
ArrayList<Question> questionArrayList = new ArrayList<>();
private String url = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<Question> getQuestions() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, 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));
questionArrayList.add(question);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
}
// 记录结果
D/Main: processFinished: []
解决方案
您可以通过以下方式传递回调
步骤1:
创建一个网吧
public interface TestCallBack {
void callBack(List<Question> response) ;
}
第二步: 创建匿名对象
TestCallBack testCallBack=new TestCallBack() {
@Override
public void callBack(List<Question> response) {
// here you will get a response after success
}
};
并将此引用传递给
questionList = new QuestionBank().getQuestions(testCallBack);
Log.d("Main", "processFinished: " + questionList);
第 3 步:
在服务器响应后调用此方法
public List<Question> getQuestions(TestCallBack testCallBack) {
public void onResponse(JSONArray response) {
testCallBack.callBack(questionArrayList); // pass your array list here
}
}
推荐阅读
- r - 使用 geom_line 和 geom_ribbon 绘制两个具有均值和 sd 的 df
- android - Android:在 SQLite 中交换数据是个好主意吗?
- json - 以字符串形式获取请求正文的 JSON 表示
- python - 当 asyncio transport.get_extra_info('peername') 返回 None 时?
- python - 如何从python中的数据框中删除“未命名”行?
- c# - 如果我的 aspnet mvc 应用程序以“.NET Core 3.1”为目标,它会针对什么点版本运行?
- python - 难以分配张量元素(张量不可散列,无法分配函数来调用)
- php - 将 GreaterThan 的选项 propertyPath 与嵌入的对象一起使用
- javascript - 当用户在 Angular 9 中关闭浏览器/选项卡时如何执行功能?
- sql - 如何在 SQL Server 中使用存储过程查找 3 个传递整数参数中的最大数字?