In RecycleView Nothing is Displayed - android

Hey guys i have this problem in android studio i just use Recycleview component and i did everything right but still Nothing Display in simulator anyone can help look up on my code..all items are just picked up from database.
item adapter for recycleview (itemadapter.kt)
class ItemAdapter (var context: Context,var list:ArrayList):
RecyclerView.Adapter(){ override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): RecyclerView.ViewHolder { var
v:View=LayoutInflater.from(context).inflate(R.layout.item_row,parent) return
ItemHolder(v) }
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position:
Int) {
(holder as ItemHolder).bind(list[position].name,list[position].price,list[position].photo)
}
class ItemHolder(itemView:View):RecyclerView.ViewHolder(itemView)
{
fun bind(n:String,p:String,u:String)
{
itemView.item_name.text =n
itemView.item_price.text=p
var web:String=" http://192.168.43.14/delivery/images/"+ u
web=web.replace("","%20")
Picasso.with(itemView.context).load(web).into(itemView.item_photo)
}
}
}
activity_item.kt
var cat:String=intent.getStringExtra("cat")
var url="http://192.168.43.14/delivery/get_items.php?category= "+cat
var list=ArrayList<Item>()
var rq: RequestQueue = Volley.newRequestQueue(this)
var jar= JsonArrayRequest(Request.Method.GET,url,null, Response.Listener { response ->
for (x in 0..response.length() -1)
list.add(Item(response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("price"),response.getJSONObject(x).getString("photo")))
var adp=ItemAdapter(this,list)
item_rv.layoutManager = LinearLayoutManager(this)
item_rv.adapter=adp
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message, Toast.LENGTH_LONG).show()
})
rq.add(jar)
}
}
Item.kt (class file)
class Item{
var id:Int
var name:String
var price:String
var photo:String
constructor(id:Int,name:String,price:String,photo:String)
{
this.id=id
this.name=name
this.price=price
this.photo=photo
}
}
please guys help me out where i mess it up beacause am stuck right there~!

You forgot to notify your list, please add the LOC adp.notifyDataSetChanged()
var adp=ItemAdapter(this,list)
item_rv.layoutManager = LinearLayoutManager(this)
item_rv.adapter=adp
adp.notifyDataSetChanged()

At first take some Tutorial to learn how to make one RecycleView Adapter and Holder:
Your Adapter should look like:
class ItemAdapter (val context: Context, val list:ArrayList<Item>): RecyclerView.Adapter<ItemHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
val v: View = LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
//.inflate(R.layout.item_row, parent, false) *false is important
return ItemHolder(v)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
holder.itemName.text = "${list[position].name}"
holder.itemPrice.text = "${list[position].price}"
val web:String="http://192.168.43.14/delivery/images/${list[position].photo}".replace(" ","%20")
Picasso.with(holder.itemView.context).load(web).into(holder.item_photo)
}
}
class ItemHolder(itemView:View):RecyclerView.ViewHolder(itemView) {
val itemName = itemView.item_name
val itemPrice = itemView.item_price
val itemPhoto = itemView.item_photo
}
You can buy me a Coffee :) for next question
FYI
var item = "item VARIABLE"
val item = "item VALUE"

Related

Android Recycleview Multiple ViewTypes not working in kotlin

I have an app which uses Room Database to show data in recycleview. It works fine when i load data seperately from different tables. But i want to show data from both tables in a single recycleview with multiple viewtypes, i know how to combine tables in room but it's not working. I get empty cards in recycleview when i load the data. Here is what i have tried so far.
My Adapter Class
class CategoriesAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val TYPE_CATEGORIES = 0
private const val TYPE_ARTICLES = 1
}
private val items: MutableList<Any> by lazy {
ArrayList<Any>()
}
fun setItems(list: List<Any>) {
items.addAll(list)
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
return if (items[position] is Categories) TYPE_CATEGORIES else TYPE_ARTICLES
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
TYPE_CATEGORIES -> CategoriesViewHolder.create(viewGroup)
else -> ArticlesViewHolder.create(viewGroup)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is CategoriesViewHolder -> {
if (items[position] is Categories)
holder.bind(items[position] as Categories)
}
is ArticlesViewHolder -> {
if (items[position] is Articles)
holder.bind(items[position] as Articles)
}
}
}
override fun getItemCount(): Int {
return items.size
}
}
class CategoriesViewHolder (parent: View) : RecyclerView.ViewHolder(parent) {
val textView: TextView = parent.findViewById(R.id.categories_textView)
fun bind(category: Categories) {
textView.text = category.categoryName
}
companion object {
fun create(parent: ViewGroup): CategoriesViewHolder {
return CategoriesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.categories_item_layout, parent, false))
}
}
}
class ArticlesViewHolder (parent: View) : RecyclerView.ViewHolder(parent) {
val textView: TextView = parent.findViewById(R.id.titleText)
fun bind(articles : Articles) {
textView.text = articles.articleName
}
companion object {
fun create(parent: ViewGroup): ArticlesViewHolder {
return ArticlesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.article_item_layout, parent, false))
}
}
}
this is how i set data from my activity
val db = AppDatabase.getDatabase(applicationContext)
dao = db.articleDao()
val recyclerView = findViewById<RecyclerView>(R.id.categories_recycle_view)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = CategoriesAdapter()
adapter.setItems(dao.getAllArticlesAndCategories())
Can anyone help.
P.s i'm new to kotlin
Instead of
adapter.setItems(dao.getAllArticlesAndCategories())
Use live data observer to avoid processing on main thread and debug in observe function of live data to confirm you are receiving correct data from DB.
calling code one line of code is missing
val db = AppDatabase.getDatabase(applicationContext)
dao = db.articleDao()
val recyclerView = findViewById<RecyclerView>(R.id.categories_recycle_view)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = CategoriesAdapter()
adapter.setItems(dao.getAllArticlesAndCategories())
it should be:
val db = AppDatabase.getDatabase(applicationContext)
dao = db.articleDao()
val recyclerView = findViewById<RecyclerView>(R.id.categories_recycle_view)
recyclerView.layoutManager = LinearLayoutManager(this)
adapter=CategoriesAdapter()
adapter.setItems(dao.getAllArticlesAndCategories())
recyclerView.adapter = adapter
I would like to thank for the question and the code

Why onLongclicklistener does no work in onBindviewholder with kotlin

I have looked for solutions to this problem but cannot find an answer.
I can get my onClickListener to work (Kotlin) from inside the onBindViewHolder of my Adapter but the onLongClickListener (Kotlin) does not respond, even though the code is not showing an error
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val ingredientdisplay=displayItems[position]
holder.setData(ingredientdisplay,position)
runningTotal=runningTotal+holder.itemView.tvcost.text.toString().toDouble()
println ("running total $runningTotal")
val intent = Intent("message_from_displayadapter")
intent.putExtra("runningtotal", runningTotal)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
holder.itemView.setOnLongClickListener {view->
println("longclick")
true
}
holder.itemView.setOnClickListener {
val intent = Intent(context, ChooseIngredientsActivity::class.java)
ContextCompat.startActivity(context, intent, null)
}
}
I am just trying to println or run a Toast but nothing happens.
I don't understand why? Your help would be appreciated.
First don't put your onClicklistiner in onBindViewHolder it's not good practice, use update your Adapter Class like this one also OnLongclicklistiner is working fine
class NewsAdapter (val context: Context, private val arrayList: ArrayList
<NewsModel>):
RecyclerView.Adapter <NewsAdapter.Holder> () {
companion object {
// val TAG: String = OperationAdapter::class.java.simpleName
}
override fun onCreateViewHolder (parent: ViewGroup, viewType: Int): Holder {
return Holder (LayoutInflater.from (parent.context ).inflate (R.layout.newsitemlist , parent, false))
}
override fun getItemCount (): Int = arrayList. size
override fun onBindViewHolder (holder: Holder, position: Int) {
val mynews= arrayList[position]
holder.setData(mynews, position)
}
inner class Holder (itemView: View): RecyclerView.ViewHolder (itemView) {
private var currentnews: NewsModel? = null
private var currentPosition: Int = 0
init {
//The click listener
itemView.cardview.setOnClickListener {
val i = Intent(context,NewsReaderActivity::class.java)
i.putExtra("body",currentnews!!.body)
i.putExtra("title",currentnews!!.title)
context.startActivity(i)
}
itemView.cardview.setOnLongClickListener{
Toast.makeText(context,"Long Clicked",Toast.LENGTH_SHORT).show()
true
}
//the end of the init
}
//getting data from model and bind it into View
fun setData(news: NewsModel?, position: Int) {
news?.let {
itemView.newstitle.text = news.title
itemView.body.text = news.body
itemView.txtdate.text = news.ndate
}
this.currentnews = news
this.currentPosition = position
}
}
}
I have moved the listeners to the inner class the code for the complete adaper is below. Still the onLongClicListener is not responding.
class RecipiesDisplayAdapter(val context:Context, val displayItems:List):RecyclerView.Adapter(){
var runningTotal:Double=0.00
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view= LayoutInflater.from(context).inflate(R.layout.recipedisplay_list,parent,false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return displayItems.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val ingredientdisplay=displayItems[position]
holder.setData(ingredientdisplay,position)
runningTotal=runningTotal+holder.itemView.tvcost.text.toString().toDouble()
println ("running total $runningTotal")
val intent = Intent("message_from_displayadapter")
intent.putExtra("runningtotal", runningTotal)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
}
inner class MyViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
private var currentIngredientDisplay:IngredientDisplay?=null
private var currentPosition:Int=0
init {
itemView.setOnLongClickListener {
Log.i ("clicked ", "longclick")
context.showToast("longClicked")
true
}
itemView.setOnClickListener {
val intent = Intent(context, ChooseIngredientsActivity::class.java)
ContextCompat.startActivity(context, intent, null)
}
}
fun setData(ingredientdisplay: IngredientDisplay?, pos:Int){
val fromrate=getfromdb(ingredientdisplay!!.unitPurchased)
val torate =getfromdb(ingredientdisplay!!.unitPerRecipe)
val minunitcost= ingredientdisplay!!.costPurchased/ingredientdisplay!!.quantityPurchased/fromrate
val costperrecipe=minunitcost*ingredientdisplay!!.quantityPerRecipe*torate
val s = String.format( "%.2f", costperrecipe);
val pdu=ingredientdisplay!!.quantityPerRecipe.toString()+" "+ingredientdisplay!!.unitPerRecipe
ingredientdisplay?.let {
itemView.tvIngredientName.text = ingredientdisplay!!.ingredientName
itemView.tvcost.text = s
itemView.tvqty.text = pdu
}
this.currentPosition=pos
this.currentIngredientDisplay=ingredientdisplay
}
fun getfromdb (unit:String) :Double{
var sendback:String=""
context.database.use {
select("Units", "convertionrate")
.`whereSimple`("unitname = ?", unit)
.exec {
parseList(DoubleParser).forEach{
println("result $it")
val resu= it.toString()
sendback=resu
}
}
}
return sendback.toDouble()
}
}
}
I cannot figure out why!
The problem is solved. I made a rookie mistake. I added all the onclicklisteners to my adapters. Then later started to add onlongclicklisteners to them. Belive it or not. I was setting it in the wrong adapter. Appologies for your trouble however your answers where helpful.
context does not work sometimes or in the newer version
so you can use also
Toast.makeText(it.context, "Long Clicked", Toast.LENGTH_SHORT).show()

Dynamic RecyclerView Adapter accepting any list

I have an app in which depending on the currency selected, I pass the list to the adapter and based on the type of list passed as an argument, I decide which model class should be used.
RecyclerView Adapter
class CoinAdapter : RecyclerView.Adapter<CoinAdapter.MyViewHolder> {
private var coinList: List<Coin>? = null
private var coinINRList: List<CoinINR>? = null
private var coinEURList: List<CoinEUR>? = null
private var coinGBPList: List<CoinGBP>? = null
private var context: Context? = null
inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var coinName: TextView
var coinPrice: TextView
init {
coinName = view.findViewById(R.id.coin_title_text)
coinPrice = view.findViewById(R.id.coin_price_text)
}
}
constructor(coinList: List<Coin>?, context: Context?) {
this.coinList = coinList
this.context = context
}
constructor(coinList: List<CoinINR>?, context: Context?, second: String) {
this.coinINRList = coinList
this.context = context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.coin_list_row, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
when (currencyUnit) {
"USD" -> {
val coin = coinList?.get(position)
holder.coinName.text = coin?.name
holder.coinPrice.text = coin?.price
}
"INR" -> {
val coinINR = coinINRList?.get(position)
holder.coinName.text = coinINR?.name
holder.coinPrice.text = coinINR?.price
}
}
}
override fun getItemCount(): Int {
when (currencyUnit) {
"USD" -> return coinList?.size ?: 0
"INR" -> return coinINRList?.size ?: 0
else -> return coinList?.size ?: 0
}
}
}
Now, I need to support multiple currencies and so the code is becoming boilerplate. Is there any way that I can make the RecyclerView accept any type of list and then perform task depending on the list?
Thanks in advance.
My suggestion is to create a class Coin that will be a parent of all other currency objects.
open class Coin(val name: String, val price: Float)
data class CoinINR(name: String, price: Float) : Coin(name, price)
Than your adapter would have only one List and your onBindViewHolder method will look like this:
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
with (coinList?.get(position)) {
holder.coinName.text = it.name
holder.coinPrice.text = it.price
}
}

Generic RecyclerView adapter

I want to have generic RecyclerView to be able to reuse it. In my case I have 2 models: CategoryImages and Category. While trying to add constructor() it brings the following errors. I know the second one is because it understands like both primary and secondary constructor are same.
Is it possible to do such kind of thing? If yes, then how? if no - thank you.
Here is CategoryImage:
class CategoryImage {
#SerializedName("url")
private var url: String? = null
fun getUrl(): String? {
return url
}
}
And here is Category:
class Category {
#SerializedName("_id")
var id: String? = null
#SerializedName("name")
var name: String? = null
#SerializedName("__v")
var v: Int? = null
#SerializedName("thumbnail")
var thumbnail: String? = null
}
Here is the part of RecyclerViewAdapter's constructor:
class RecyclerViewAdapter(var arrayList: ArrayList<CategoryImage>?, var fragment: Int): RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
constructor(arrayList: ArrayList<Category>, fragment: Int): this(arrayList, fragment)
}
I want to have generic RecyclerView to be able to reuse it.
That's nice intention, then why you haven't made your adapter generic?
I think you can adopt the approach outlined by Arman Chatikyan in this blog post. After applying some Kotlin magic you'll only need following lines of code in order to setup your RecyclerView:
recyclerView.setUp(users, R.layout.item_layout, {
nameText.text = it.name
surNameText.text = it.surname
})
And if you need to handle clicks on RecyclerView items:
recyclerView.setUp(users, R.layout.item_layout, {
nameText.text = it.name
surNameText.text = it.surname
}, {
toast("Clicked $name")
})
Now the adapter of the RecyclerView is generic and you are able to pass list of any models inside setup() method's first argument.
In this section I will copy-paste sources from the blog post, in order to be evade from external sources deprecation.
fun <ITEM> RecyclerView.setUp(items: List<ITEM>,
layoutResId: Int,
bindHolder: View.(ITEM) -> Unit,
itemClick: ITEM.() -> Unit = {},
manager: RecyclerView.LayoutManager = LinearLayoutManager(this.context)): Kadapter<ITEM> {
return Kadapter(items, layoutResId, {
bindHolder(it)
}, {
itemClick()
}).apply {
layoutManager = manager
adapter = this
}
}
class Kadapter<ITEM>(items: List<ITEM>,
layoutResId: Int,
private val bindHolder: View.(ITEM) -> Unit)
: AbstractAdapter<ITEM>(items, layoutResId) {
private var itemClick: ITEM.() -> Unit = {}
constructor(items: List<ITEM>,
layoutResId: Int,
bindHolder: View.(ITEM) -> Unit,
itemClick: ITEM.() -> Unit = {}) : this(items, layoutResId, bindHolder) {
this.itemClick = itemClick
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.itemView.bindHolder(itemList[position])
}
override fun onItemClick(itemView: View, position: Int) {
itemList[position].itemClick()
}
}
abstract class AbstractAdapter<ITEM> constructor(
protected var itemList: List<ITEM>,
private val layoutResId: Int)
: RecyclerView.Adapter<AbstractAdapter.Holder>() {
override fun getItemCount() = itemList.size
override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(layoutResId, parent, false)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val item = itemList[position]
holder.itemView.bind(item)
}
protected abstract fun onItemClick(itemView: View, position: Int)
protected open fun View.bind(item: ITEM) {
}
class Holder(itemView: View) : RecyclerView.ViewHolder(itemView)
}
Assuming CategoryImage means a Category with image.
You can express this relationship with inheritance:
open class Category(
val name: String
)
class CategoryImage(
name: String,
val image: String
) : Category(name)
class RecyclerViewAdapter(
val arr: List<Category>,
val fragment: Int
) {
fun bind(i: Int) {
val item = arr[i]
val name: String = item.name
val image: String? = (item as? CategoryImage)?.image
}
}
Another options it to have a common interface (which removes that ugly cast):
interface CategoryLike {
val name: String
val image: String?
}
class Category(
override val name: String
) : CategoryLike {
override val image: String? = null
}
class CategoryImage(
override val name: String,
override val image: String
) : CategoryLike
class RecyclerViewAdapter(private var arr: List<CategoryLike>, var fragment: Int) {
fun bind(i: Int) {
val item = arr[i]
val name: String = item.name
val image: String? = item.image
}
}
In both cases the following works (just to see that it can be compiled):
fun testCreation() {
val cats: List<Category> = listOf()
val catImages: List<CategoryImage> = listOf()
RecyclerViewAdapter(cats, 0)
RecyclerViewAdapter(catImages, 0)
}
Tip: don't use ArrayList, List (listOf(...)) or MutableList (mutableListOf(...)) should be enough for all your needs.
Tip: try to use val as much as you can, it helps prevent mistakes.
Wish: Next time please also include some relevant parts of your code in a copy-able form (not screenshot), so we don't have to re-type it and have more context. See https://stackoverflow.com/help/mcve
One "terrible" way of doing it is to simply have 1 constructor taking an ArrayList of Objects and perform an instanceof on the objects.
Both methods have the same signature, because type parameters are not considered as different types (for Java Virtual Machine both are just ArrayLists). You also need to be aware of type erasure.
Check this repository https://github.com/shashank1800/RecyclerGenericAdapter
lateinit var adapter: RecyclerGenericAdapter<AdapterItemBinding, TestModel>
...
val clickListener = ArrayList<CallBackModel<AdapterItemBinding, TestModel>>()
clickListener.add(CallBackModel(R.id.show) { model, position, binding ->
Toast.makeText(context, "Show button clicked at $position", Toast.LENGTH_SHORT)
.show()
})
adapter = RecyclerGenericAdapter(
R.layout.adapter_item, // layout for adapter
BR.testModel, // model variable name which is in xml
clickListener // adding click listeners is optional
)
binding.recyclerView.adapter = adapter
binding.recyclerView.layoutManager = LinearLayoutManager(this)
adapter.submitList(viewModel.testModelList)
Recycler adapter item R.layout.adapter_item XML.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="testModel"
type="com.packagename.model.TestModel" />
</data>
...
VERY IMPORTANT NOTE: I'm using same layout for all my screens.
//********Adapter*********
// include a template parameter T which allows Any datatype
class MainAdapter<T : Any>(var data: List<T>) : RecyclerView.Adapter<MainViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
val view = parent.inflateLayout()
return MainViewHolder(view)
}
override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
val item = data[position]
holder.bind(item)
}
override fun getItemCount(): Int = data.size
class MainViewHolder(private val binding: MainItemsListBinding) :
RecyclerView.ViewHolder(binding.root) {
// do the same for for bind function on Viewholder
fun <T : Any> bind(item: T) {
// Extension function see code below
binding.appInfo.mySpannedString(item)
}
}
}
//Cast Item to type
fun <T : Any> TextView.mySpannedString(item: T) {
when (item.javaClass.simpleName) {
"AaProgram" -> {
item as AaProgram
this.text = buildSpannedString {
appInfo(item.numero, item.principio)
}
}
"AppContent" -> {
item as AppContent
this.text = buildSpannedString {
appInfo(item.title, item.coment, item.footnote)
}
}
"AutoDiagnostic" -> {
item as AppContent
this.text = buildSpannedString {
appInfo(item.title, item.coment, item.footnote)
}
}
"GroupDirectory" -> {}
"ReflexionsBook" -> {}
"County" -> {}
"States" -> {}
"Towns" -> {}
}
}

recyclerview onClick getkey from firebase

How do I get key in kotlin in RecyclerView to send it to another activity?
I tried using getKey() and position but it doesn't work.
Here is my code:
class RecyclerAdapter (val userlist:ArrayList<RecyClass>,ccc: Context): RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
var mcontext =ccc
val Postdata = java.util.ArrayList<RecyClass>()
lateinit var ref:DatabaseReference
override fun getItemCount(): Int {
return userlist.size
}
override fun onBindViewHolder( holder: ViewHolder?, position: Int) {
val user: RecyClass = userlist[position]
ref = FirebaseDatabase.getInstance().getReference(user.toString())
holder?.txtviewdesc?.text = user.desc
Picasso.with(mcontext).load(user.image).into(holder?.imageviewx)
holder?.setOncustomcilcklistner(object :Custumclicklistner33{
override fun oncustomOnClickListner(view: View, pos: Int) {
}
})
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
this.Postdata
this.mcon
val v = LayoutInflater.from(parent?.context).inflate(R.layout.layoutrcview,parent,false)
return ViewHolder(v,mcon,userlist)
}
class ViewHolder(itemview: View,ccc2:Context,userlist: ArrayList<RecyClass>): RecyclerView.ViewHolder(itemview), View.OnClickListener{
var mCustIemClick5: Custumclicklistner33?=null
var txtviewdesc: TextView
var mcon =ccc2
var userdata =userlist
var imageviewx: ImageView
init {
this.userdata
this.mcon
txtviewdesc = itemview.findViewById<TextView>(R.id.editTextdesc)
imageviewx = itemview.findViewById<ImageView>(R.id.imgvw)
itemview.setOnClickListener(this)
}
fun setOncustomcilcklistner(customclick5: Custumclicklistner33){
this.mCustIemClick5=customclick5
}
override fun onClick(view: View?) {
this.mCustIemClick5!!.oncustomOnClickListner(view!!,adapterPosition)
val pos = adapterPosition
val ref =FirebaseDatabase.getInstance().getReference(pos.toString()).key.toString()
Toast.makeText(mcon,ref,Toast.LENGTH_LONG).show()
var postDetail = this.userdata[pos]
val kkk = Intent(this.mcon,ProfileActivity::class.java)
kkk.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
this.mcon.startActivity(kkk)
}
}
}
fun onclick takes to next activity but it takes post's key. How to get it?
getref and postiton is not working in fun onclick but it works on bindviewholder.
You need to use PostData[position] to get the object that current position and then a key/field from that object that you can reference.

Categories

Resources