Blank screen with RecyclerView No adapter attached

房东的猫 提交于 2019-12-13 03:46:38

问题


I'm tying to parse JSON in recyclerview. App compiles fine but it's outputting empty/blank screen

BlogAdapter.kt

class BlogAdapter(private val blogList: List<Blog>) : RecyclerView.Adapter<BlogAdapter.ViewHolder>() {


    override fun getItemCount()= blogList.size

    private var mContext: Context? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        this.mContext=parent.context;

        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.character_item,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val mBlog = this.blogList[position]

        if (mBlog.img != null) {
            Glide.with(mContext!!)
                .load(mBlog.img)
                .into(holder.ivThumbnail)
        }
        if (mBlog.name != null) {
            holder.tvTitle.text = mBlog.name
            println("Log: Kabe "+mBlog.name)
        }
    }

    class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        val ivThumbnail:ImageView = itemView.findViewById(R.id.ivThumbnail);
        val tvTitle:TextView = itemView.findViewById(R.id.tvTitle);
    }
}

MainActivity.kt

class MainActivity : AppCompatActivity() {

    var mainViewModel: MainViewModel? = null
    var mBlogAdapter: BlogAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        getPopularBlog()
        swipe_refresh.setOnRefreshListener { getPopularBlog() }
    }

    private fun getPopularBlog() {
        swipe_refresh.isRefreshing = false
        mainViewModel!!.allBlog.observe(this, Observer {  charactersList ->
            prepareRecyclerView(charactersList)
        })

    }

    private fun prepareRecyclerView(blogList: List<Blog>) {

        mBlogAdapter = BlogAdapter(blogList)
        if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
            blogRecyclerView.layoutManager = LinearLayoutManager(this)
        } else {
            blogRecyclerView.layoutManager = GridLayoutManager(this, 4)
        }
        blogRecyclerView.itemAnimator = DefaultItemAnimator()
        blogRecyclerView.adapter = mBlogAdapter

    }
}

My Json file looks like this:

[
  {
    "id": 1,
    "name": "potter",
    "img": "https://images.example.com/potter.jpg"
},
{ …}
]

I've created it based on this tutorial: https://itnext.io/kotlin-wrapping-your-head-around-livedata-mutablelivedata-coroutine-networking-and-viewmodel-b552c3a74eec

Any suggestions please

EDIT:

class BlogRepository() {

    private var character = mutableListOf<ABCCharacters>()
    private var mutableLiveData = MutableLiveData<List<ABCCharacters>>()
    val completableJob = Job()
    private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)

    private val thisApiCorService by lazy {
        RestApiService.createCorService()
    }

    fun getMutableLiveData():MutableLiveData<List<ABCCharacters>> {
        coroutineScope.launch {
            val request = thisApiCorService.getPopularBlog()
            withContext(Dispatchers.Main) {
                try {

                    val response = request.await()
                    val mBlogWrapper = response;
                    if (/*mBlogWrapper != null &&*/ mBlogWrapper.isNotEmpty()) {
                        character = mBlogWrapper as MutableList<ABCCharacters>
                        mutableLiveData.value = character
                    }

                } catch (e: HttpException) {
                    // Log exception //

                } catch (e: Throwable) {
                    // Log error //)
                }
            }
        }
        return mutableLiveData;
    }
}

回答1:


You forget to call notifyDataSetChanged, when you setup your RecyclerView widget. Below the full method call, to make it works.

private fun prepareRecyclerView(blogList: List<Blog>) {

    mBlogAdapter = BlogAdapter(blogList)
    if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
        blogRecyclerView.layoutManager = LinearLayoutManager(this)
    } else {
        blogRecyclerView.layoutManager = GridLayoutManager(this, 4)
    }
    blogRecyclerView.itemAnimator = DefaultItemAnimator()
    blogRecyclerView.adapter = mBlogAdapter
    mBlogAdapter.notifyDataSetChanged()

}



回答2:


Try using below implementation:

class MainActivity : AppCompatActivity() {

    lateinit var mainViewModel: MainViewModel
    var mBlogAdapter: BlogAdapter? = null
    var blogList: List<Blog> = arrayListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        // init your RV here 
        prepareRecyclerView()
        getPopularBlog()
        swipe_refresh.setOnRefreshListener { mainViewModel.getAllBlog() }
    }

    private fun getPopularBlog() {
        swipe_refresh.isRefreshing = false
        mainViewModel.getAllBlog().observe(this, Observer {  charactersList ->
           blogList = charactersList
           mBlogAdapter?.notifyDataSetChanged()
        })
    }

    private fun prepareRecyclerView() {

        mBlogAdapter = BlogAdapter(blogList)
        if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
            blogRecyclerView.layoutManager = LinearLayoutManager(this)
        } else {
            blogRecyclerView.layoutManager = GridLayoutManager(this, 4)
        }
        blogRecyclerView.itemAnimator = DefaultItemAnimator()
        blogRecyclerView.adapter = mBlogAdapter

    }
}

Modify your view model like below:

class MainViewModel() : ViewModel() {

    val characterRepository= BlogRepository()

    fun getAllBlog(): MutableLiveData<List<ABCCharacters>> {
        return characterRepository.getMutableLiveData()
    }

    override fun onCleared() {
        super.onCleared()
        characterRepository.completableJob.cancel()
    }
}


来源:https://stackoverflow.com/questions/58825330/blank-screen-with-recyclerview-no-adapter-attached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!