RecyclerView возвращает пустой


Я искал вокруг, и ничего, кажется, не работает. У меня есть объект RecyclerView, и он работал отлично, если я не пытался создать событие слушателя бесконечной прокрутки. После этого он перестает работать и возвращает пустой вид. Поэтому я удалил код, который добавил, Но он все еще тот же. Я прилагаю файлы для дальнейших ссылок.

Фрагмент

public class Questions extends Fragment {

    List<QuestionsItem> questionsItems;
    String beforeString = "";
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_questions, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        // Equivalent to on Create
        super.onViewCreated(view, savedInstanceState);

        getActivity().setTitle("Questions");

        recyclerView = view.findViewById(R.id.question_recycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        questionsItems = loadQuestions("recent", "all", beforeString, "0");

        adapter = new QuestionsAdapter(questionsItems, getContext());

        recyclerView.setAdapter(adapter);


    }

    public List<QuestionsItem> loadQuestions(String sort, String area, String before, String length) {
        final List<QuestionsItem> questions = new ArrayList<>();
        final API api = new API();

        OkHttpClient client = new OkHttpClient();

        RequestBody body = new FormBody.Builder()
                .add("sort", sort)
                .add("area", area)
                .add("before", before)
                .add("length", length)
                .build();

        Request request = api.call("q_loadmore", body, getContext(), getActivity());

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                MaterialDialog dialog = api.prepareDialog(getContext(), "An Error Occoured", "An Error Occoured. Please make sure you are connected to the internet and try again. If the issue still persists please contact support.");
                dialog.show();
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                        try {
                            JSONObject jsonObject = new JSONObject(responseText);

                            if (jsonObject.get("status").equals("ok"))
                            {
                                JSONObject payload = jsonObject.getJSONObject("payload");
                                JSONArray questionsArray = payload.getJSONArray("questions");

                                // TODO: Set Before String
                                //beforeString = payload.get("before").toString();

                                for (int i=0; i < questionsArray.length(); i++) {
                                    JSONObject obj = questionsArray.getJSONObject(i);
                                    String id = obj.get("qid").toString();
                                    String title = obj.get("title").toString();
                                    String postedBy = obj.get("postedBy").toString();
                                    int views = obj.getInt("views");
                                    int votes = obj.getInt("votes");
                                    int answers = obj.getInt("answers");
                                    int postedOn = obj.getInt("postedOn");
                                    String[] tags = api.toStringArray(obj.getJSONArray("tags"));

                                    QuestionsItem questionsItem = new QuestionsItem(id, title, tags, views, votes, answers, postedBy, postedOn);
                                    questions.add(questionsItem);
                                }

                            }
                            else if (jsonObject.get("status").equals("error"))
                            {
                                MaterialDialog dialog = api.prepareDialog(getContext(), jsonObject.getJSONObject("dialog").get("title").toString(), jsonObject.getJSONObject("dialog").get("message").toString());
                                dialog.show();
                            }
                            else
                            {
                                MaterialDialog dialog = api.prepareDialog(getContext(), "An Error Occurred", "An Error Occurred. Please make sure you are connected to the internet and try again. If the issue still persists please contact support.");
                                dialog.show();
                            }

                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }
            }
        });

        return questions;
    }

}

Адаптер

public class QuestionsAdapter extends RecyclerView.Adapter<QuestionsAdapter.ViewHolder> {

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView title;
        public TextView date;
        public TextView username;
        public TextView stats;
        public AutoLabelUI labels;

        public ViewHolder(View itemView) {
            super(itemView);

            title = itemView.findViewById(R.id.ques_title);
            date = itemView.findViewById(R.id.ques_time);
            username = itemView.findViewById(R.id.ques_username);
            stats = itemView.findViewById(R.id.ques_stats);
            labels = itemView.findViewById(R.id.ques_labels);

        }
    }

    private List<QuestionsItem> questionsItems;
    private Context context;

    public QuestionsAdapter(List<QuestionsItem> questionsItems, Context context) {
        this.questionsItems = questionsItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_questions, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        QuestionsItem questionsItem = questionsItems.get(position);

        holder.title.setText(questionsItem.getTitle());
        holder.date.setText(DateTimeUtils.getTimeAgo(context, new Date(questionsItem.getPostedOn()), DateTimeStyle.AGO_FULL_STRING));
        holder.username.setText("@" + questionsItem.getPostedBy());
        holder.stats.setText(questionsItem.getViews() + " views  " + questionsItem.getVotes() + " votes  " + questionsItem.getAnswers() + " answers");

        AutoLabelUISettings autoLabelUISettings = new AutoLabelUISettings.Builder()
                .withMaxLabels(5)
                .withShowCross(false)
                .withLabelsClickables(false)
                .build();

        holder.labels.setSettings(autoLabelUISettings);

        String[] tags = questionsItem.getTags();

        for (String tag: tags) {
            holder.labels.addLabel(tag);
        }


    }

    @Override
    public int getItemCount() {
        return questionsItems.size();
    }

}

Модель

public class QuestionsItem {

    private String id;
    private String title;
    private String[] tags;
    private int views;
    private int votes;
    private int answers;
    private String postedBy;
    private int postedOn;

    public QuestionsItem(String id, String title, String[] tags, int views, int votes, int answers, String postedBy, int postedOn) {
        this.id = id;
        this.title = title;
        this.tags = tags;
        this.views = views;
        this.votes = votes;
        this.answers = answers;
        this.postedBy = postedBy;
        this.postedOn = postedOn;
    }

    public String getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String[] getTags() {
        return tags;
    }

    public int getViews() {
        return views;
    }

    public int getVotes() {
        return votes;
    }

    public int getAnswers() {
        return answers;
    }

    public String getPostedBy() {
        return postedBy;
    }

    public int getPostedOn() {
        return postedOn;
    }

}
1 2

1 ответ:

В момент, когда вы возвращаете вопросы в loadQuestions (), он пуст, потому что обратный вызов onresponse выполняется после ответа сервера.

В класс адаптера добавьте метод setQuestions, который задает вопросы.

public void setQuestions(List<QuestionsItem> questions) {
    this.questions = questions;
}

В onResponse добавьте следующее:

  // return void here
    public void loadQuestions(String sort, String area, String before, String length) {
    final List<QuestionsItem> questions = new ArrayList<>();
    final API api = new API();

    OkHttpClient client = new OkHttpClient();

    RequestBody body = new FormBody.Builder()
            .add("sort", sort)
            .add("area", area)
            .add("before", before)
            .add("length", length)
            .build();

    Request request = api.call("q_loadmore", body, getContext(), getActivity());

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            MaterialDialog dialog = api.prepareDialog(getContext(), "An Error Occoured", "An Error Occoured. Please make sure you are connected to the internet and try again. If the issue still persists please contact support.");
            dialog.show();
            call.cancel();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            final String responseText = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(responseText);

                        if (jsonObject.get("status").equals("ok"))
                        {
                            JSONObject payload = jsonObject.getJSONObject("payload");
                            JSONArray questionsArray = payload.getJSONArray("questions");

                            // TODO: Set Before String
                            //beforeString = payload.get("before").toString();

                            for (int i=0; i < questionsArray.length(); i++) {
                                JSONObject obj = questionsArray.getJSONObject(i);
                                String id = obj.get("qid").toString();
                                String title = obj.get("title").toString();
                                String postedBy = obj.get("postedBy").toString();
                                int views = obj.getInt("views");
                                int votes = obj.getInt("votes");
                                int answers = obj.getInt("answers");
                                int postedOn = obj.getInt("postedOn");
                                String[] tags = api.toStringArray(obj.getJSONArray("tags"));

                                QuestionsItem questionsItem = new QuestionsItem(id, title, tags, views, votes, answers, postedBy, postedOn);
                                questions.add(questionsItem);
                            }



                       // Set questions array in your adapter class
                       mQuestionAdapter.setQuestions(questions);
                       mQuestionAdapter.notifyDatasetChanged();



                        }
                        else if (jsonObject.get("status").equals("error"))
                        {
                            MaterialDialog dialog = api.prepareDialog(getContext(), jsonObject.getJSONObject("dialog").get("title").toString(), jsonObject.getJSONObject("dialog").get("message").toString());
                            dialog.show();
                        }
                        else
                        {
                            MaterialDialog dialog = api.prepareDialog(getContext(), "An Error Occurred", "An Error Occurred. Please make sure you are connected to the internet and try again. If the issue still persists please contact support.");
                            dialog.show();
                        }

                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
        }
    });
// remove return statement
}