0

It works fine until PagingDataEpoxyController but when passing data to EpoxyModel the apk crashes. This is my code, plaese help me

@EpoxyModelClass 
abstract class PostCommentModel : EpoxyModel() {

  @EpoxyAttribute
  lateinit var commentData : CommentData

  override fun getDefaultLayout() : Int {
     return R.layout.layout_comment_item
  }

  override fun bind(view: LayoutCommentBinding) {
         super.bind(view)
         view.profileName.text = commentData.username
           ...
    }
}


class PostCommentController( private val context: Context ) : PagingDataEpoxyController<CommentData>() {
      override fun buildItemModel(currentPosition: Int, item: CommentData?): EpoxyModel<*> {
          return PostCommentModel()_
                   .id(item!!.id)
                   .commentData(item)
      }
}

How to make Epoxymodel usable with PagingDataEpoxyController?, Thank you...

B_B
  • 1

1 Answers1

0

You should add your crash logs as well so that we can know for sure where the issue lies.

By the look of the code you provided, I am almost certain that you're having a NullPointerException so I will answer accordingly.

If you read the javadoc for PagingDataEpoxyController#buildItemModel, it mentions that it passes in null values as a way of telling you that you should supply your UI with some placeholders (in order to hint the users that more items are being loaded at the moment).

/**
 * Builds the model for a given item. This must return a single model for each item. If you want
 * to inject headers etc, you can override [addModels] function.
 *
 * If the `item` is `null`, you should provide the placeholder. If your [PagedList] is
 * configured without placeholders, you don't need to handle the `null` case.
 */
abstract fun buildItemModel(currentPosition: Int, item: T?): EpoxyModel<*>

You're forcing a nullable value to be force-unwrapped even though Epoxy tells you that it may be null sometimes. Hence your app crashes with NullPointerException. You should never do a force-unwrap !! if you're not 100% sure that the value can not be null.

So instead of doing:

override fun buildItemModel(currentPosition: Int, item: CommentData?): EpoxyModel<*> {
      return PostCommentModel()_
               .id(item!!.id) // You are force unwrapping a nullable value here
               .commentData(item)
  }

you should be doing something like:

override fun buildItemModel(currentPosition: Int, item: CommentData?): EpoxyModel<*> {
      return if (item != null) {
         PostCommentModel()_
               .id(item.id) // No need force-unwrapping now! We are safe from a NullPointerException
               .commentData(item)
      } else {
         PlaceholderModel()_
              .id("placeholder-$currentPosition")
      }
  }

Here we checked whether or not the item is null, and showed a Placeholder when it is.

I hope this helps you!

Onur D.
  • 515
  • 3
  • 11