带RecyclerView的黑屏未连接适配器 [英] Blank screen with RecyclerView No adapter attached

查看:121
本文介绍了带RecyclerView的黑屏未连接适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在recyclerview中解析JSON.应用编译正常,但输出空白/黑屏

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

BlogAdapter.kt

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

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

    }
}

我的Json文件如下:

My Json file looks like this:

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

我是根据本教程创建的: https://itnext.io/kotlin-wrapping-your-head-around-livedata-mutablelivedata-coroutine-networking-and-viewmodel-b552c3a74eec

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

请提出任何建议

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;
    }
}

推荐答案

尝试使用以下实现:

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()
    }
}

这篇关于带RecyclerView的黑屏未连接适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆