Cannot post Picasso image into recyclerview viewholder in Kotlin - kotlin

I am currently working on a project in Kotlin and I'm having trouble working an image into a ViewHolder through Picasso and keep getting requests to create an extension function instead when troubleshoot. This is where the problem comes in
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val user = mUser[position]
holder.userNameTextView.text = user.getUsername()
holder.userFullNameTextView.text = user.getFullName()
Picasso.get().load(user.getImage())
.placeholder(R.drawable.ic_user_avatar_light)
.into(holder.userProfileImageView)
... with the rest of my adapter being this
class SearchAdapter(private var mContext: Context,
private var mUser: List<User>,
private var isFragment: Boolean = false) : RecyclerView.Adapter<SearchAdapter.ViewHolder>() {
private var firebaseUser: FirebaseUser? = FirebaseAuth.getInstance().currentUser
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.user_item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val user = mUser[position]
holder.userNameTextView.text = user.getUsername()
holder.userFullNameTextView.text = user.getFullName()
Picasso.get().load(user.getImage())
.placeholder(R.drawable.ic_user_avatar_light)
.into(holder.userProfileImageView)
user.getUid()?.let { checkWatchingStatus(it, holder.userWatchButton as Button) }
holder.itemView.setOnClickListener{
val pref = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit()
pref.putString("profileID", user.getUid())
pref.apply()
(mContext as FragmentActivity).supportFragmentManager.beginTransaction()
.replace(R.id.viewPager, ProfileFragment()).commit()
}
holder.userWatchButton.setOnClickListener{
if(holder.userWatchButton.text.toString() == "Watch"){
firebaseUser?.uid.let{ itl ->
user.getUid()?.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Watch").child(itl.toString())
.child("Watching").child(it1)
.setValue(true).addOnCompleteListener{ task ->
if (task.isSuccessful){
firebaseUser?.uid.let{ itl ->
FirebaseDatabase.getInstance().reference
.child("Watch").child(user.getUid()!!)
.child("Watchers").child(itl.toString())
.setValue(true).addOnCompleteListener{ task ->
if (task.isSuccessful){
}
}
}
}
}
}
}
} else {
firebaseUser?.uid.let{ itl ->
user.getUid()?.let { it1 ->
FirebaseDatabase.getInstance().reference
.child("Watch").child(itl.toString())
.child("Watching").child(it1)
.removeValue().addOnCompleteListener{ task ->
if (task.isSuccessful){
firebaseUser?.uid.let{ itl ->
FirebaseDatabase.getInstance().reference
.child("Watch").child(user.getUid()!!)
.child("Watchers").child(itl.toString())
.removeValue().addOnCompleteListener{ task ->
if (task.isSuccessful){
}
}
}
}
}
}
}
}
}
}
override fun getItemCount(): Int {
return mUser.size
}
class ViewHolder(#NonNull itemView: View) :RecyclerView.ViewHolder(itemView) {
var userNameTextView: TextView = itemView.findViewById(R.id.userName_search)
var userFullNameTextView: TextView = itemView.findViewById(R.id.userFullName_search)
var userProfileImageView: TextView = itemView.findViewById(R.id.userImage_search)
var userWatchButton: TextView = itemView.findViewById(R.id.watchButton_search)
}
private fun checkWatchingStatus(uid: String, userWatchButton: Button){
val watchingRef = firebaseUser?.uid.let{ itl ->
FirebaseDatabase.getInstance().reference
.child("Watch").child(itl.toString())
.child("Watching")
}
watchingRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
if (p0.child(uid).exists()) {
userWatchButton.text = "Watching"
} else {
userWatchButton.text = "Watch"
}
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
}
Can anyone help?

In your ViewHolder, you're declaring userProfileImageView as a TextView not as an ImageView, and passing that into Picasso's into() method, which accepts an ImageView as a parameter, that is why it is asking to create an extension function.
class ViewHolder(#NonNull itemView: View) :RecyclerView.ViewHolder(itemView) {
var userNameTextView: TextView = itemView.findViewById(R.id.userName_search)
var userFullNameTextView: TextView = itemView.findViewById(R.id.userFullName_search)
//declare userProfileImageView as an ImageView
var userProfileImageView: ImageView = itemView.findViewById(R.id.userImage_search)
var userWatchButton: TextView = itemView.findViewById(R.id.watchButton_search)
}

Related

Problem with recyclerview last item added not showed inside a fragment

I having problem showing the last item when I update my recyclerview. The data is correct but I have to scroll down to show the last item because is out of screen. It's not a problem about constraint, nor margins, I've double checked it.I've read several posts here about how to fix it but none has worked for my code so far. Any suggestions?
This is my adapter:
class ComentarioAdaptador(private var context: Context, private var publicacionLista: ArrayList<Comentario>): RecyclerView.Adapter<ComentarioAdaptador.ViewHolder>()
{
private var tipoUsuario=""
class ViewHolder( itemView: View):RecyclerView.ViewHolder(itemView) {
var ivPerfil : ImageView = itemView.findViewById(R.id.iv_perfil)
var tvNombreUsuario: TextView = itemView.findViewById(R.id.tv_propietario)
var tvComentario: TextView = itemView.findViewById(R.id.tv_comentario)
var tvFecha: TextView = itemView.findViewById(R.id.tv_fecha)
var btnBorrar: Button =itemView.findViewById(R.id.brn_borrar_comentario)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =LayoutInflater.from(context).inflate(R.layout.comentario,parent,false)
determinarTipoUsuario()
return ViewHolder(view)
}
override fun getItemCount(): Int {
return publicacionLista.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val comentario = publicacionLista[position]
holder.tvComentario.text =comentario.contenido
holder.tvFecha.text= comentario.fecha
buscarUsuario(holder.ivPerfil, holder.tvNombreUsuario, comentario.creadoPor,holder.btnBorrar)
holder.btnBorrar.setOnClickListener{
}
}
private fun buscarUsuario(ivPerfil: ImageView, tvNombreUsuario: TextView, propietario: String, btnBorrar:Button) {
val usuarioRef = FirebaseDatabase.getInstance().reference.child("Usuarios").child(propietario)
usuarioRef.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
val usuario=snapshot.getValue(Usuario::class.java)
tvNombreUsuario.text=usuario!!.usuario
Glide.with(context).load(usuario.perfil).circleCrop().into(ivPerfil)
if (tipoUsuario=="usuario")
btnBorrar.isGone=true
else
btnBorrar.isVisible=true
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun determinarTipoUsuario(){
val usuarioActual = FirebaseAuth.getInstance().currentUser!!
val userID = usuarioActual.uid
//LUEGO HAGO UNA INSTANCIA DE ESA UID
val busqueda = FirebaseDatabase.getInstance().getReference("Usuarios").child(userID)
//FINALMENTE LE PONGO UN LISTENER PARA GUARDAR DATOS
busqueda.addValueEventListener(object : ValueEventListener
{
override fun onDataChange(snapshot: DataSnapshot)
{
tipoUsuario = snapshot.getValue(Usuario::class.java)!!.tipo
Toast.makeText(context, tipoUsuario, Toast.LENGTH_SHORT).show()
}
override fun onCancelled(error: DatabaseError)
{}
})
}
}
This is how I call the the recyclerview on my fragment:
private fun mostrarComentarios(uidPostRecibido:String){
val comentariosRef= FirebaseDatabase.getInstance().reference.child("Comentarios").child(uidPostRecibido)
listaComentarios!!.clear()
comentariosRef.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (snapshot in snapshot.children)
{
val comentario = snapshot.getValue(Comentario::class.java)
listaComentarios!!.add(comentario!!)
}
comentarioAdaptador!!.notifyDataSetChanged()
}
}
override fun onCancelled(error: DatabaseError) {
}
}
)
}

Show item info on selected item in RecyclerView using Kotlin

I am using kotlin language with android studio. I want to get the properties of the element I clicked in the RecyclerView.
Ben bu kod ile saderc id alabiliyorum
Ex: date
ListAdapter.kt
class ListAdapter(
private val context: Context
) : RecyclerView.Adapter<ListAdapter.ListViewHolder>() {
private var dataList = mutableListOf<Any>()
private lateinit var mListener: onItemClickListener
interface onItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener) {
mListener = listener
}
fun setListData(data: MutableList<Any>) {
dataList = data
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
return ListViewHolder(view)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val question: Questionio = dataList[position] as Questionio
holder.bindView(question)
}
override fun getItemCount(): Int {
return if (dataList.size > 0) {
dataList.size
} else {
return 0
}
}
inner class ListViewHolder(itemView: View, listener: onItemClickListener) :
RecyclerView.ViewHolder(itemView) {
fun bindView(questionio: Questionio) {
itemView.findViewById<TextView>(R.id.txt_policlinic).text = questionio.policlinic
itemView.findViewById<TextView>(R.id.txt_title).text = questionio.title
itemView.findViewById<TextView>(R.id.txt_description).text = questionio.description
itemView.findViewById<TextView>(R.id.txt_date).text = questionio.date
itemView.findViewById<TextView>(R.id.txt_time).text = questionio.time
}
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
}
My code in onCreateView inside list fragment.Edit
ListFragment
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.adapter = adapter
observeData()
adapter.setOnItemClickListener(object : ListAdapter.onItemClickListener {
override fun onItemClick(position: Int) {
showShortToast(position.toString())
}
})
this function is also my observationData(),
I made new edits
private fun observeData() {
binding.shimmerViewContainer.startShimmer()
listViewModel.fetchQuestinData("questions",
requireContext())
.observe(viewLifecycleOwner, {
binding.shimmerViewContainer.startShimmer()
binding.shimmerViewContainer.hideShimmer()
binding.shimmerViewContainer.hide()
adapter.setListData(it)
adapter.notifyDataSetChanged()
})
}
You can pass highOrderFuction into the adapter then setonclickListener for any view you want. Like this:
class ListAdapter(
private val context: Context,
private val onItemClick:(questionio: Questionio)->Unit
) : RecyclerView.Adapter<ListAdapter.ListViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
return ListViewHolder(view,onItemClick)
}
...
inner class ListViewHolder(itemView: View,private val onItemClick:(questionio: Questionio)->Unit) : RecyclerView.ViewHolder(itemView) {
fun bindView(questionio: Questionio) {
//set on any view you want
itemView.findViewById<TextView>(R.id.root_view_id).
setOnClickListener{onItemClick(questionio)}
itemView.findViewById<TextView>(R.id.txt_policlinic).text =
questionio.policlinic
itemView.findViewById<TextView>(R.id.txt_title).text = questionio.title
itemView.findViewById<TextView>(R.id.txt_description).text =
questionio.description
itemView.findViewById<TextView>(R.id.txt_date).text = questionio.date
itemView.findViewById<TextView>(R.id.txt_time).text = questionio.time
}
}
}

Recyclerview does not display on the screen in kotlin

So I tried to create multi views recyclerview in kotlin, but sadly it did not work.The recyclerview does not display on the screen. It worth to mention that I tried to set the orientation as vertical in my layout files, also added all the dependencies and things needed. Can anyone please help me with that?
My MainActivity.class
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var adapter: NumbersAdapter
lateinit var recyclerView: RecyclerView
var list: List<Nums> = listOf(Nums(1,false))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
updateAll()
}
fun updateAll(){
binding.recyclerview.apply {
val layoutManager = LinearLayoutManager(this#MainActivity)
adapter = NumbersAdapter(list)
adapter = adapter
}}}
My Adapter
class NumbersAdapter(
var list: List<Nums>,
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
class RedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val name = itemView.findViewById<TextView>(R.id.red_number)
fun bindRed(number: Nums) {
name.text = number.nums.toString()
}
}
class OrangeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val name = itemView.findViewById<TextView>(R.id.orange_number)
fun bindOrange(number: Nums) {
name.text = number.nums.toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == 0) {
val redvView =
LayoutInflater.from(parent.context).inflate(R.layout.red_item, parent, false)
return RedViewHolder(redvView)
}
else {
val orangeView =
LayoutInflater.from(parent.context).inflate(R.layout.orange_item, parent, false)
return OrangeViewHolder(orangeView)
}
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if(getItemViewType(position)==0){
(holder as RedViewHolder).bindRed(list[position])
}
else{
(holder as OrangeViewHolder).bindOrange(list[position])
}
}
override fun getItemViewType(position: Int): Int {
checkItem()
if(list[position].flag)
return 0
return 1
}
fun checkItem(){
for (i in list.indices) {
for (k in i + 1 until list.size) {
if (list[i].nums + list[k].nums == 0) {
list[i].flag = true
list[k].flag = true
}}}}}
in MainActivity.class change code in updateAll() function
fun updateAll(){
binding.recyclerView.apply {
adapter = NumbersAdapter(list)
layoutManager = LinearLayoutManager(this#MainActivity)
}
}

Items randomly appears in RecyclerView

I have made a simple app for taking notes, it works fine. When i scrolled up or down the screen, they are randomly expanded or shows previous screen states when scrolled as seen here screen1 (no scrolling) and screen2 (when scrolled)
Any help is very much appreciated.
My adapter code is below:
class NoteListAdapter : RecyclerView.Adapter<NoteListAdapter.ViewHolder>(), {
private var wordList: List<EnEntity> = arrayListOf()
private var filteredWordList: List<EnEntity> = arrayListOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(
R.layout.note_list,
parent, false
)
return ViewHolder(view)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(word: EnEntity) {
itemView.zk_entitle.text = word.titleWord
itemView.zk_custword.text = word.customWord
itemView.note_list_main.setOnClickListener {
val action = EnFragmentDirections.actionEnFragmentToNoteFragment(word)
itemView.findNavController().navigate(action)
}
//the eye icon
itemView.zk_eye.setOnClickListener {
if (itemView.zk_custword.isGone) {
itemView.zk_custword.visibility = View.VISIBLE
itemView.zk_eye.setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP)
} else {
itemView.zk_custword.visibility = View.GONE
itemView.zk_eye.clearColorFilter()
}
}
if (word.isFavorite) {
itemView.zk_faved.visibility = View.VISIBLE
} else{
View.GONE
}
/** show heart icon*/
itemView.zk_faved.setOnClickListener {
if (itemView.zk_faved_deson.isGone) {
itemView.zk_faved_deson.visibility = View.VISIBLE
}
}
itemView.zk_faved.setOnLongClickListener {
val t = Toast.makeText(itemView.context, "Favorite", Toast.LENGTH_SHORT)
t.setGravity(Gravity.TOP, 0, 60)
t.show()
true
}
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//search
holder.bind(filteredWordList[position])
}
override fun getItemCount(): Int = filteredWordList.size
fun setAllWords(wordItems: List<EnEntity>) {
this.wordList = wordItems
this.filteredWordList = wordItems
notifyDataSetChanged()
}
}
Try applying setHasStableIds(true) to your adapter
like so:
class NoteListAdapter : RecyclerView.Adapter<NoteListAdapter.ViewHolder>(), {
init {
setHasStableIds(true)
}
Then add the following two functions inside your adapter class
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getItemViewType(position: Int): Int {
return position
}

Item on recycler-view disappear after changing to a different activity and back again

A very newbie programmer here and not a good English typer. Im trying to create a checker for purchase that already made previous using the PurchaseHistoryResponseListener. And When a checker found something, it will add to a list and then feed the recyclerview_MYBook with that data. The issue is that when launching the app, the data is flow through the recyclerview_MYBook perfectly, but when moving to different activity and going back to the previous activity through a different method (button click) the data on the recyclerview_MYBook doesn't show up, only through a conventional back button, the data on the recyclerview show up. Below here is my noob code
class MainActivity : AppCompatActivity(), PurchasesUpdatedListener {
private lateinit var billingClient: BillingClient
private lateinit var blogadapternew: BlogRecyclerAdapterNew
private lateinit var blogadapterpremium: BlogRecyclerAdapterPremium
private lateinit var blogadapterfree: BlogRecyclerAdapterFree
private lateinit var blogadaptermybook: BlogRecyclerAdapterMyBook
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
auth = FirebaseAuth.getInstance()
//FirebaseAuth.getInstance().signOut()
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.activity_main)
recycler_viewNew.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL,false)
recycler_viewNew.adapter= BlogRecyclerAdapterNew()
recycler_viewPremium.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
recycler_viewPremium.adapter= BlogRecyclerAdapterPremium()
recycler_viewFree.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
recycler_viewFree.adapter= BlogRecyclerAdapterFree()
recycler_viewMyBook.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
recycler_viewMyBook.adapter= BlogRecyclerAdapterMyBook()
if (supportActionBar != null)
supportActionBar?.hide()
setupBillingClient()
initrecyclerView()
initrecyclerViewPremium()
initrecyclerViewFree()
initrecyclerViewMyBook()
addDataSetNew()
addDataSetPremium()
addDataSetFree()
Logo.setOnClickListener{
val intent = Intent(MonstaLogo.context, MainActivity::class.java)
MonstaLogo.context.startActivity(intent)
}
MainFeaturedButton.setOnClickListener {
val intent = Intent(MainFeaturedButton.context, MainActivity::class.java)
MainFeaturedButton.context.startActivity(intent)
}
MainNewButton.setOnClickListener {
val intent = Intent(MainNewButton.context, NewActivity::class.java)
MainNewButton.context.startActivity(intent)
}
NewMore.setOnClickListener{
val intent = Intent(NewMore.context, NewActivity::class.java)
NewMore.context.startActivity(intent)
}
MainPremiumButton.setOnClickListener {
val intent = Intent(MainPremiumButton.context, PremiumActivity::class.java)
MainPremiumButton.context.startActivity(intent)
}
PremiumMore.setOnClickListener{
val intent = Intent(PremiumMore.context, PremiumActivity::class.java)
PremiumMore.context.startActivity(intent)
}
MainFreeButton.setOnClickListener {
val intent = Intent(MainFreeButton.context, FreeActivity::class.java)
MainFreeButton.context.startActivity(intent)
}
FreeMore.setOnClickListener {
val intent = Intent(FreeMore.context, FreeActivity::class.java)
FreeMore.context.startActivity(intent)
}
MainMyBookButton.setOnClickListener {
val intent = Intent(MainMyBookButton.context, MyBookActivity::class.java)
MainMyBookButton.context.startActivity(intent)
}
MyBookMore.setOnClickListener {
val intent = Intent(MyBookMore.context, MyBookActivity::class.java)
MyBookMore.context.startActivity(intent)
}
}
private fun setupBillingClient() {
billingClient = BillingClient.newBuilder(this)
.enablePendingPurchases()
.setListener(this)
.build()
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
println("Setup Billing Done")
PurchaseHistoryResponseListener()
}
}
override fun onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
println("Failed")
setupBillingClient()
println("Restart Connection")
}
})
}
override fun onPurchasesUpdated(
billingResult: BillingResult?,
purchases: MutableList<Purchase>?
) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private fun PurchaseHistoryResponseListener (){
billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP) {
responseCode, result ->
// println("queryPurchasesAsync INAPP results: ${result?.size}")
// println("Getting Purchase History")
println("$result")
val dataMyBook1 = DataSourceMyBook.createDataSet()
if ("testcode1" in result.toString()) {
println("found it 1")
dataMyBook1.add((BlogPost( "BookName","Link","No")))
}
if ("testcode2" in result.toString()) {
println("found it 2")
dataMyBook1.add((BlogPost( "BookName","Link","No")))
}
if ("testcode3" in result.toString()) {
println("found it 3")
dataMyBook1.add((BlogPost( "BookName","Link","No")))
}
blogadaptermybook.submitList(dataMyBook1)
println(dataMyBook1)
}
}
private fun addDataSetNew(){
val dataNew = DataSourceNew.createDataSet()
blogadapternew.submitList(dataNew)
}
private fun addDataSetPremium(){
val dataPremium = DataSourcePremium.createDataSet()
blogadapterpremium.submitList(dataPremium)
}
private fun addDataSetFree(){
val dataFree = DataSourceFree.createDataSet()
blogadapterfree.submitList(dataFree)
}
/*private fun addDataSetMyBook(){
val dataMyBook1 = DataSourceMyBook.createDataSet()
blogadaptermybook.submitList(dataMyBook1)
}*/
/*private fun addDataSetMyBook(){
val dataMyBook1 = DataSourceMyBook.createDataSet()
billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP) {
responseCode, result ->
println("$result")
if ("bbbg_s2_c1_testcode1" in result.toString()){
dataMyBook1.add((BlogPost( "Mini Comic 1","Link","No")))
}
if ("bbbg_s2_c1_testcode2" in result.toString()){
dataMyBook1.add((BlogPost( "Mini Comic 2","Link","No")))
}
if ("bbbg_s2_c1_testcode3" in result.toString()){
dataMyBook1.add((BlogPost( "Mini Comic 3","Link","No")))
}
blogadaptermybook.submitList(dataMyBook1)
}}*/
/*dataMyBook.add((BlogPost( "Mini Comic 1","Link","No")))
dataMyBook.add((BlogPost( "Mini Comic 1","Link","No")))
dataMyBook.add((BlogPost( "Mini Comic 1","Link","No")))*/
private fun initrecyclerView(){
recycler_viewNew.apply {
layoutManager = LinearLayoutManager(this#MainActivity,RecyclerView.HORIZONTAL,false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadapternew = BlogRecyclerAdapterNew()
adapter = blogadapternew
}
}
private fun initrecyclerViewPremium(){
recycler_viewPremium.apply {
layoutManager = LinearLayoutManager(this#MainActivity,RecyclerView.HORIZONTAL,false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadapterpremium = BlogRecyclerAdapterPremium()
adapter = blogadapterpremium
}
}
private fun initrecyclerViewFree(){
recycler_viewFree.apply {
layoutManager = LinearLayoutManager(this#MainActivity,RecyclerView.HORIZONTAL,false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadapterfree = BlogRecyclerAdapterFree()
adapter = blogadapterfree
}
}
private fun initrecyclerViewMyBook(){
recycler_viewMyBook.apply {
layoutManager =
LinearLayoutManager(this#MainActivity, RecyclerView.HORIZONTAL, false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadaptermybook = BlogRecyclerAdapterMyBook()
adapter = blogadaptermybook
}
}
public override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
updateUI(currentUser)
}
private fun updateUI(currentUser: FirebaseUser?) {
if (currentUser != null) {
AccountSettingButton.setImageResource(R.drawable.profileicon)
}
}
}
Here is adapter
class BlogRecyclerAdapterMyBook : RecyclerView.Adapter() {
private var items: List<BlogPost> = ArrayList()
private var items2: List<BlogPost> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return BlogViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.layout_blog_list_item_mybook,
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is BlogViewHolder -> {
holder.bind(items.get(position))
holder.bind(items2.get(position))
}
}
}
override fun getItemCount(): Int {
return items.size
}
fun submitList(bloglist: List<BlogPost>) {
items = bloglist
items2 = bloglist
}
class BlogViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
val blogImage: ImageButton = itemView.blog_imagemybook
val blogTitle: TextView = itemView.blog_titlemybook
val premiumImage: ImageView = itemView.premiumicon
fun bind(blogPost: BlogPost) {
blogTitle.setText(blogPost.title)
val requestOptions = RequestOptions()
.placeholder(R.drawable.mocksplash)
.error(R.drawable.disconnect)
Glide.with(itemView.blog_imagemybook)
.applyDefaultRequestOptions(requestOptions)
.load(blogPost.image)
.into(blogImage)
blogImage.setOnClickListener {
Toast.makeText(blogImage.context, "<<Swipe left<<", Toast.LENGTH_SHORT).show()
val intent = Intent(blogTitle.context, ComicReadingActivity::class.java)
var KomikName = blogTitle.text.toString()
intent.putExtra("KomikName",Name)
blogImage.context.startActivity(intent)
}
}
}
}
and here the data source file where that will store the data for the adapter
class DataSourceMyBook{
companion object{
fun createDataSet(): ArrayList<BlogPost> {
val dataMyBook1 = ArrayList<BlogPost>()
return dataMyBook1
}
}
}