首页 > 解决方案 > 为什么即使我在请求期间向其中添加了元素,此代码也会显示一个空数组列表?

问题描述

我的代码是这样的,我不知道为什么它得到一个空数组,即使我在请求期间将元素添加到数组中。

公共类 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: []

标签: javaandroidarraysandroid-volley

解决方案


您可以通过以下方式传递回调

步骤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
 }

}

推荐阅读