Search code examples
androidkotlinparsingandroid-recyclerviewjsoup

List items don't come to screen but printed on console


I am trying to parse website using Jsoup. When I run the app, the parsed items come to console, I mean with println statements, but the list of items doesn't come to recyclerview of the fragment, just a blank screen appears. The code part is long, I am pasting the whole fragment(with recyclerview) and adapter codes here. Any help is appreciated.

Adapter Class:

class ExampleAdapter : RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>() {
//    ExampleAdapter(private val exampleList: List<Books>)
    private val exampleList = mutableListOf<Books>()

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

    override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {    
//        val currentItem = exampleList[position]
//        holder.imageView.setImageResource(currentItem.imageResource)
//        holder.textView1.text = currentItem.title
//        holder.textView2.text = currentItem.description
//        holder.textView3.text = currentItem.additionalInfo
        holder.bind(exampleList[position])
    }
    override fun getItemCount(): Int = exampleList.size

    class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.row_img
        val textView1: TextView = itemView.row_tv_title
        val textView2: TextView = itemView.row_tv_description
        val textView3: TextView = itemView.row_tv_additional_info

        fun bind(books: Books) {
            textView1.text = books.title
            textView2.text = books.description
            Picasso.with(itemView.context)
                .load(books.imageResource)
                .transform(CropSquareTransformation())
                .into(imageView)
            textView3.text = books.additionalInfo
//        link = books.linkDetails
        }
    }

    //exampleList class içindeki val değerlerini silmeyince unresolved reference hatası veriyor:
    fun set(list: MutableList<Books>) {
        this.exampleList.clear()
        this.exampleList.addAll(list)
        notifyDataSetChanged()
    }

}


class CropSquareTransformation : Transformation {
    override fun transform(source: Bitmap): Bitmap {
        val size = Math.min(source.width, source.height)
        val x = (source.width - size) / 2
        val y = (source.height - size) / 2
        val result = Bitmap.createBitmap(source, x, y, size, size)
        if (result != source) {
            source.recycle()
        }
        return result
    }

    override fun key(): String {
        return "square()"
    }

Fragment Class:

class ListBooksFragment : Fragment() {

    private lateinit var adapter: ExampleAdapter
    private val url ="https://openlibrary.org/search?q=men&mode=everything"
    private val exampleList = mutableListOf<Books>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        recycler_view.layoutManager = LinearLayoutManager(this.context)
        adapter = ExampleAdapter()
        recycler_view.adapter = ExampleAdapter()

        GlobalScope.launch {
            getData()
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list_books, container, false)
    }

    companion object {

        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            ListBooksFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }



    private fun getData(){

        val list = ArrayList<Books>()

        try {
            val document = Jsoup.connect(url).get()
            val elements = document.select("li.searchResultItem")

            for (i in 0 until elements.size) {
                val title = elements.select("div.resultTitle")
                    .select("a.results")
                    .eq(i)
                    .text()

                println("title = " + title.toString())

//                AUTHOR:
//                val author = elements.select("span.bookauthor")
//                    .select("a.results")
//                    .eq(i)
//                    .text()

                val description = elements.select("span.bookauthor")
                    .select("a.results")
                    .eq(i)
                    .text()

                println("description = " + description.toString())

                val linkImage = "https://www.tutorialspoint.com/images/QAicon.png"
//                    document.baseUri() +
//                    elements.select("div[class=bookcover]")
//                        .select("img")
//                        .eq(i)
//                        .attr("src")

                val additionalInfo = elements.select("span.resultPublisher")
                    .select("span.publishedYear")
                    .eq(i)
                    .text()

                println("additionalInfo = " + additionalInfo.toString())

                exampleList.add(Books(imageResource = R.drawable.ic_launcher_background, title, description, additionalInfo))

               //Below 2 lines are just for another approach
                val item = Books(imageResource = R.drawable.ic_launcher_background, title, description, additionalInfo)
                list += item

            }
            GlobalScope.launch(Dispatchers.Main) {
                adapter.set(exampleList)
            }
        } catch (e: IOException) {
            Log.e("TEST EXCEPTION:::: ", e.message.toString())
        }
    }
}

Solution

  • You are loading the list into an adapter instance which is not associated with the RecyclerView, if you look closely in onActivityCreated, you will see that you are doing

    adapter = ExampleAdapter()              // New instance of ExampleAdapter assigned to adapter property
    recycler_view.adapter = ExampleAdapter()// New instance of ExampleAdapter assigned to RV
    

    and then you are loading the list as

    adapter.set(exampleList)   // This adapter is not associated with the RV
    

    to fix this change the above lines in onActivityCreated to

    adapter = ExampleAdapter()
    recycler_view.adapter = adapter