在无尽的回收者视图中的分页与firebase

Ris*_*rya 3 pagination android firebase android-recyclerview firebase-realtime-database

我正在开发Q/A应用程序.我已成功加载firebase的问题.但我无法从Firebase中应用分页数据库.如何识别我们已经到达了回收站视图的末尾,以便可以加载下几个问题.

Pha*_*inh 7

要认识到我们已经达到RecyclerView你的目的,你可以使用这个类EndlessRecyclerOnScrollListener.java

要加载更多下一个问题,您应该在相同的Question class数字中再定义一个字段

public class Question {
    private int number; // it must unique and auto increase when you add new question
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后当你从中加载问题时FireBase可以这样做

public class MainActivity extends AppCompatActivity {
    private static final int TOTAL_ITEM_EACH_LOAD = 10;
    private DatabaseReference mDatabase;
    final List<Question> questionList = new ArrayList<>();

    private int currentPage = 0;

    private RecyclerView recyclerView;
    private RecyclerViewAdapter mAdapter; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // init and set layout manager for your RecyclerView
        ...
        mAdapter = new RecyclerViewAdapter(questionList);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
            @Override
            public void onLoadMore(int current_page) { // when we have reached end of RecyclerView this event fired
                loadMoreData();
            }
        });
        loadData(); // load data here for first time launch app
    }

    private void loadData() {
        // example
        // at first load : currentPage = 0 -> we startAt(0 * 10 = 0)
        // at second load (first loadmore) : currentPage = 1 -> we startAt(1 * 10 = 10)
        mDatabase.child("questions")
                .limitToFirst(TOTAL_ITEM_EACH_LOAD)
                .startAt(currentPage*TOTAL_ITEM_EACH_LOAD)
                .orderByChild("number")
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(!dataSnapshot.hasChildren()){
                            Toast.makeText(MainActivity.this, "No more questions", Toast.LENGTH_SHORT).show();
                            currentPage--;
                        }
                        for (DataSnapshot data : dataSnapshot.getChildren()) {
                            Question question = data.getValue(Question.class);
                            questionList.add(question);
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                   @Override public void onCancelled(DatabaseError databaseError) {}});
    }

    private void loadMoreData(){
        currentPage++;
        loadData();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的DEMO项目

  • @RishabhMaurya 来自 1 级 (2认同)