почему этот код показывает пустой список массивов, хотя я добавил элементы во время запроса? - PullRequest
0 голосов
/ 26 сентября 2019

мой код такой, я не знаю, почему он получает пустой массив, хотя я добавил элементы в массив во время запроса.

открытый класс 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: []

Ответы [ 2 ]

1 голос
/ 26 сентября 2019

Вы можете передать обратный вызов следующим образом

шаг 1:

Создать Intercafe

public interface TestCallBack {
        void callBack(List<Question> response) ;
}

Шаг 2: создать анонимные объекты

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
 }

}
1 голос
/ 26 сентября 2019

Он пуст, потому что вы заполняете его асинхронно .Вы должны добавить обратный вызов в качестве параметра, вызвать его в onResponse.

...