0
votes

Second Activity

class BookDescription : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_book_description)

    var books = intent.getParcelableExtra("String") as Book
    Glide.with(this).load(books.imageUrl).into(bookImg1)
    nameTxt1.text = books.name
    autorTxt1.text = books.name
} }

Adapter class

class Adapter(private val context: Context) : RecyclerView.Adapter<Adapter.Holder>() {

private var datalist = mutableListOf<Book>()
fun setListdata(data: MutableList<Book>){
    datalist = data
}

inner class Holder(itemView : View) : RecyclerView.ViewHolder(itemView){
     fun bindView(book: Book){
         Glide.with(context).load(book.imageUrl).into(itemView.bookImg)
         itemView.nameTxt.text = book.name
         itemView.autorTxt.text= book.writer

         itemView.bookImg.setOnClickListener(
                 View.OnClickListener {
                     val intent = Intent(context, BookDescription::class.java)
                     intent.putExtra("jbg", book)
                     context.startActivity(intent)
                 }
         )
     }
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
    val view = LayoutInflater.from(context).inflate(R.layout.book_format, parent,

false ) return Holder(view) }

override fun onBindViewHolder(holder: Holder, position: Int) {
       val book = datalist[position]
       holder.bindView(book)
}

override fun getItemCount(): Int {
   return if (datalist.size> 0){
        datalist.size
    }else{
        0
    }
} }

Main Activity

class MainActivity : AppCompatActivity() {

private lateinit var adapter : Adapter
private val viewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java)}

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

    adapter = Adapter(this)
    recycle.layoutManager = GridLayoutManager(this,2)
    recycle.adapter = adapter
    observerData()
}

   fun observerData(){
       viewModel.fetchUserData().observe(this,Observer{
           adapter.setListdata(it)
           adapter.notifyDataSetChanged()
       })
   }

}

Class Book

@Parcelize data class Book(val imageUrl:String= "URL IMmage", val name:String = "Naziv knjige", val writer:String= "Pisac knjige") :Parcelable!

1

1 Answers

0
votes

You need to make sure that your Book class implements Parcelable, and then make sure that the key used to put the extra matches the key used to retrieve it:

Adapter

val intent = Intent(context, BookDescription::class.java)
intent.putParcelable("UNIQUE_KEY", book)
context.startActivity(intent)

BookDescription

var books = intent.getParcelableExtra("UNIQUE_KEY") as Book