0

Los datos en el RecyclerView se llaman la primera vez sin problemas. Sin embargo, cuando refresco los datos, por alguna razón todos los elementos se quedan en blanco.

La Actividad Principal es esta

class BusinessActivity : AppCompatActivity() {

    private val businessViewModel: BusinessViewModel by viewModel()
    private val imageLoader: ImageLoader by inject()
    private lateinit var staggeredGridLayoutManager: StaggeredGridLayoutManager
    private lateinit var skeleton: Skeleton
    private val adapter: BusinessAdapter by lazy { BusinessAdapter(imageLoader, businessViewModel) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_business)
        initToolbar()
        skeleton = findViewById<SkeletonLayout>(R.id.skeletonLayout)
        staggeredGridLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        staggeredGridLayoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS
        recycler_view.apply {
            layoutManager = staggeredGridLayoutManager
            adapter = [email protected]
            setHasFixedSize(true)
        }
        setupSkeleton()
        initializeObserverBusiness()
        refreshBusiness.setOnRefreshListener {
            refreshBusiness.isRefreshing = true
            skeleton.showSkeleton()
            businessViewModel.retrieveBusiness()
        }
    }

    private fun initToolbar() {
        setSupportActionBar(toolbar)
        supportActionBar?.title = getString(R.string.app_name)
        this.setSystemBarColor(this)
    }

    private fun setupSkeleton(){
        skeleton = recycler_view.applySkeleton(R.layout.business_card, 6)
        skeleton.showSkeleton()
    }

    private fun initializeObserverBusiness(){
        businessViewModel.uiState.observe(this, Observer {
            val dataState = it ?: return@Observer
            if (!dataState.showProgress){
                refreshBusiness.isRefreshing = false
                skeleton.showOriginal()
            }
            if (dataState.business != null && !dataState.business.consumed){
                dataState.business.consume()?.let { business ->
                    adapter.submitList(business)
                }
            }
            if (dataState.error != null && !dataState.error.consumed){
                dataState.error.consume()?.let { error ->
                    Toast.makeText(this, resources.getString(error), Toast.LENGTH_LONG).show()
                }
            }
        })
    }
}

y el Adaptador para el RecyclerView, actualmente estoy usando DiffCallback y ListAdapter debido a un mejor rendimiento.

class BusinessAdapter(var imageLoader: ImageLoader, var viewModel: BusinessViewModel) : ListAdapter<Business, BusinessViewHolder>(DIFF_CALLBACK){
    companion object{
        private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Business>() {
            override fun areItemsTheSame(oldItem: Business, newItem: Business) = oldItem.id == newItem.id
            override fun areContentsTheSame(oldItem: Business, newItem: Business) = oldItem == newItem
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = BusinessViewHolder.create(parent)

    override fun onBindViewHolder(holder: BusinessViewHolder, position: Int) {
        holder.bind(getItem(position), imageLoader, viewModel)
    }
}

y el ViewHolder para el Adaptador.

class BusinessViewHolder constructor(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer {

    fun bind(business: Business, imageLoader: ImageLoader, viewModel: BusinessViewModel) {
        businessImage?.let { imageLoader.load("${BuildConfig.MY_URL}/gallery/${business.images[0]}", it) }
        ownerBusiness.text = business.owner
        businessName.text = business.name
        cardBusiness.setOnClickListener {
            viewModel.callDetailBusiness(business.id)
        }
    }

    companion object {
        fun create(parent: ViewGroup): BusinessViewHolder {
            return BusinessViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.business_card, parent, false))
        }
    }
}

y el ViewModel.

class BusinessViewModel (private val businessRepository: BusinessRepository): ViewModel() {
    private val _uiState = MutableLiveData<BusinessDataState>()
    val uiState: LiveData<BusinessDataState> get() = _uiState
    val _showDetailBusiness = MutableLiveData<Int?>()
    val showDetailBusiness: LiveData<Int?> get() = _showDetailBusiness

    init {
        retrieveBusiness()
    }

    fun retrieveBusiness(){
        viewModelScope.launch {
                runCatching {
                    emitUiState(showProgress = true)
                    businessRepository.retrieveBusiness()
                }.onSuccess {
                    emitUiState(business = Event(it))
                }.onFailure {
                    emitUiState(error = Event(R.string.internet_failure_error))
                }
        }
    }

    fun callDetailBusiness(businessId: Int) {
        _showDetailBusiness.value = businessId
    }

    private fun emitUiState(showProgress: Boolean = false, business: Event<List<Business>>? = null, error: Event<Int>? = null){
        val dataState = BusinessDataState(showProgress, business, error)
        _uiState.value = dataState
    }

    data class BusinessDataState(val showProgress: Boolean, val business: Event<List<Business>>?, val error: Event<Int>?)
}

Cuando los datos se cargan por primera vez, veo esto. PrimarCarga

sin embargo, cuando aplico el SwipeRefresh. Recibo los datos.

D/OkHttp:[{"id":18, "name": "Whatsup", "owner": "Mi Soledad", "categoría": "ToDo",

pero el RecyclerView no adjuntará la nueva información.... DataPerdida

Porfavor necesito que me ayuden a saber como solventar esta situación... Gracias.

4
  • enq ue momento ejecutas el SwipeRefresh? Commented el 5 nov. 2019 a las 16:43
  • @IgmerRodriguez es en esta seccion: refreshBusiness.setOnRefreshListener { refreshBusiness.isRefreshing = true skeleton.showSkeleton() businessViewModel.retrieveBusiness() } Commented el 5 nov. 2019 a las 17:03
  • retrieveBusiness() no tiene algo relacionado a cargar información en el adapter!
    – Jorgesys
    Commented el 5 nov. 2019 a las 18:18
  • RetrieveBusiness manda a cargar la data en el LiveData... y en el observer se manda a validar... Commented el 5 nov. 2019 a las 19:17

1 respuesta 1

0

Segun logro entender en tu codigo, cargas el layoutmanager del recycler aqui

staggeredGridLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
    staggeredGridLayoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS
    recycler_view.apply {
        layoutManager = staggeredGridLayoutManager
        adapter = [email protected]
        setHasFixedSize(true)
    }

Cuando se hace el Refresh del layout y termine de cargar nuevamente los datos debes asignar nuevamente el layoutmanager o preferiblemente notificar de cambios al adapter del recycler asi

my_recycler.adapter!!.notifyDataSetChanged()

Recuerda que debes hacerlo despues que se han actualizado los datos de la lista que deseas mostrar en ese recycler

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.