1

I am trying to implement Pagination in My project but i don't how it loads all the data from Firestore.

I tried my Own method to Paginate but i don't where i am wrong with pagination.

Code :

Assigned Variable

lateinit var adapter: BooksListAdapter
var booksArray = arrayListOf<Book>()
var totalItemCount: Int = 0
var lastVisibleItem : Int = 0
var visibleThreshold : Int = 0
var item_count = 6
private var loading : Boolean = false

Layout Manager and Adapter Declaration

val mLayoutManager = LinearLayoutManager(this)
books_list.setLayoutManager(mLayoutManager)
adapter = BooksListAdapter(arrayListOf(), singlePage, multiplePage, this)
books_list.adapter = adapter

Data Load in First View

private fun getBooksData() {
    bookCollection
            .orderBy("created_at", Query.Direction.DESCENDING)
            .limit(item_count.toLong()).get()
            .addOnSuccessListener { booksSnapshot ->
                if (!booksSnapshot.isEmpty) {
                    for (bookSnapShot in booksSnapshot.documents) {
                        val hashmap = bookSnapShot.data
                        hashmap?.put("id", bookSnapShot.id)
                        val bookData = Gson().toJson(hashmap)
                        val book = Gson().fromJson<Book>(bookData, Book::class.java)
                        booksArray.add(book)
                    }
                    shimmer_view_container_book.stopShimmerAnimation()
                    shimmer_view_container_book.setVisibility(View.GONE)
                    rcv_book.setVisibility(View.VISIBLE)
                    adapter.booksList.addAll(booksArray)
                    adapter.notifyDataSetChanged()
                }
            }
            .addOnFailureListener { exception ->
                Toast.makeText(this, exception.message, Toast.LENGTH_SHORT).show()
            }

}

and my onaddScrollListener :

    books_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView,
                                dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            visibleThreshold = books_list.getChildCount();
            totalItemCount = mLayoutManager.getItemCount()
            lastVisibleItem = mLayoutManager
                    .findLastVisibleItemPosition()
            if (!loading && totalItemCount <= lastVisibleItem + visibleThreshold) {
                getMoreBooks(adapter.getLastBook())
                loading = true

            }
        }
    })

Get More books :

private fun getMoreBooks(lastBook: Timestamp) {
    bookCollection
            .orderBy("created_at", Query.Direction.DESCENDING)
            .startAfter(lastBook)
            .limit(item_count.toLong()).get()
            .addOnSuccessListener {booksSnapshot ->
                if (!booksSnapshot.isEmpty) {
                    for (bookSnapShot in booksSnapshot.documents) {
                        val hashmap = bookSnapShot.data
                        hashmap?.put("id", bookSnapShot.id)
                        val bookData = Gson().toJson(hashmap)
                        val book = Gson().fromJson<Book>(bookData, Book::class.java)
                        adapter.addDatainList(book)
                    }
                }
            }
}

Adapter :

class BooksListAdapter (var booksList: ArrayList<Book>, val singlePage: View.OnClickListener, val multiplePage: View.OnClickListener, val context : Context): RecyclerView.Adapter<BooksListAdapter.ViewHolder>() {
    var bookid = ""
    val storageReference = FirebaseStorage.getInstance()

    fun getLastBook(): Timestamp{
        return booksList.get(booksList.size-1).created_at
    }

    fun addDatainList(book : Book){
       booksList.add(book)
       notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.single_book, parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return booksList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (booksList.get(position).picture != "null"){
            GlideApp.with(context).load(booksList[position].picture?.let { storageReference.reference.child(it) }).centerCrop().override(300, 300).into(holder.bookImage!!)
        }else{
            GlideApp.with(context).load(R.drawable.picture).centerCrop().override(300, 300).into(holder.bookImage!!)
        }
        holder.bookCard!!.setOnClickListener {
            if (booksList[position].pages > 1){
                bookid = booksList.get(position).id
                multiplePage.onClick(it)
            }else{
                bookid = booksList.get(position).id
                singlePage.onClick(it)
            }
        }
        holder.bookTitle!!.setText(booksList[position].book_name)
        holder.bookPages!!.setText("Book Pages : ${booksList[position].pages}")
        holder.bookAuther!!.setText(booksList[position].auther)
        holder.bookDescription!!.setText(booksList[position].book_description)
    }


    class ViewHolder (itemView: View) : RecyclerView.ViewHolder(itemView) {
        var bookCard: CardView? = null
        var bookTitle: TextView? = null
        var bookDescription: TextView? = null
        var bookPages: TextView? = null
        var bookAuther: TextView? = null
        var bookImage : ImageView? = null
        init {
            this.bookCard = itemView.findViewById(R.id.single_book_card)
            this.bookTitle = itemView.findViewById(R.id.book_title_txt)
            this.bookDescription = itemView.findViewById(R.id.book_desc_txt)
            this.bookAuther = itemView.findViewById(R.id.auther_txt)
            this.bookPages = itemView.findViewById(R.id.book_pages)
            this.bookImage = itemView.findViewById(R.id.book_img)
        }
    }
}

Thank you in Advance

If you want ill provide other info

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ashish
  • 6,791
  • 3
  • 26
  • 48
  • 1
    You can check **[this](https://stackoverflow.com/questions/50741958/how-to-paginate-firestore-with-android)** out. It's an working example. It's in Java but I think you can understand it. – Alex Mamo Jun 11 '19 at 12:31
  • @AlexMamo explanation in that answer is better to understand cause i been researching lot for Pagination but there was no clue how to do pagination. – Ashish Jun 11 '19 at 12:42
  • @AlexMamo it helped me to under it works Thanks – Ashish Jun 11 '19 at 13:17
  • Good to hear that ;) – Alex Mamo Jun 11 '19 at 13:21

2 Answers2

2

My example hope it help

  page = 0
    var previous = 0
    val viewth = 20
      recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        visible = gridLayoutManager.childCount
                        total = gridLayoutManager.itemCount
                        past = gridLayoutManager.findFirstVisibleItemPosition()
                        if (dy > 0) {
                            if (loading) {
                                if (total > previous) {
                                    loading = false
                                    previous = total
                                }
                            }
                            if (!loading && (total - visible) <= (past + viewth)) {
                                page++
                                getNextData(page.toString(), range)//call your next set
                                loading = true
                            }
                        } else {
                            mSwipeRefreshLayout.isEnabled = gridLayoutManager.findFirstCompletelyVisibleItemPosition() == 0
                        }

                    }

                    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                        super.onScrollStateChanged(recyclerView, newState)
                        mSwipeRefreshLayout.isEnabled = gridLayoutManager.findFirstCompletelyVisibleItemPosition() == 0
                    }

                })
Praveen
  • 946
  • 6
  • 14
0

try to edit Git More Book like this

private fun getMoreBooks(lastBook: Timestamp) {
    bookCollection
            .orderByChild("created_at", Query.Direction.DESCENDING)
            .equalTo(lastBook)
            .limitToFirst(10).get()
            .addOnSuccessListener {booksSnapshot ->
                if (!booksSnapshot.isEmpty) {
                    for (bookSnapShot in booksSnapshot.documents) {
                        val hashmap = bookSnapShot.data
                        hashmap?.put("id", bookSnapShot.id)
                        val bookData = Gson().toJson(hashmap)
                        val book = Gson().fromJson<Book>(bookData, Book::class.java)
                        adapter.addDatainList(book)
                    }
                }
            }
}
Ashish
  • 6,791
  • 3
  • 26
  • 48
Mohammad Sommakia
  • 1,773
  • 3
  • 15
  • 48