Delete item in Arraylist in RecyclerView within Adapter - android

I'm having trouble to delete one item in my Arraylist from Firebase Database using RecyclerView. There is an AlertDialog which I can see when I'm clicking on it, but it doesn't delete the Item. I think the problem is, that I cannot get the postID correctly. But I tried it in many ways, and within the database Reference I wasn't able to do it right.
This is where I add the Post to the database:
val ref = FirebaseDatabase.getInstance().reference.child("Posts")
val postId = ref.push().key
And here you can see my PostsAdapter
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.posts_layout, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return mPosts.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
FirebaseUser = FirebaseAuth.getInstance().currentUser
val posts = mPosts[position]
holder.title.text = posts.getTitle()
holder.content.text = posts.getContent()
holder.deletePost.text = posts.getPostId()
ownerInfo(holder.name, posts.getOwner())
}
inner class ViewHolder(#NonNull itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
override fun onClick(p0: View?) {
val intent = Intent(itemView.context, DeletePostActivity::class.java)
// here pass id through intent
intent.putExtra("postId", R.id.deletePost)
itemView.context.startActivity(intent)
}
var title: TextView
var content: TextView
var owner: TextView
var name: TextView
var deletePost: Button
init{
title = itemView.findViewById(R.id.post_title)
content = itemView.findViewById(R.id.post_content)
owner = itemView.findViewById(R.id.post_owner)
name = itemView.findViewById(R.id.post_owner)
deletePost = itemView.findViewById(R.id.post_delete)
deletePost.setOnClickListener{
AlertDialog.Builder(mContext)
.setTitle("Löschen")
.setMessage("Wollen Sie diesen Post wirklich löschen?")
.setCancelable(true)
.setPositiveButton("Ja") { dialog, which ->
notifyItemRemoved(adapterPosition)
notifyItemRangeChanged(adapterPosition, mPosts.size)
val postsRef = FirebaseDatabase.getInstance().reference.child("Posts").child("postID")
postsRef.child("postID").removeValue()
}
.create()
.show()
}
}
}

Actually you are not passing any postID to delete. Check below
Instead of
val postsRef = FirebaseDatabase.getInstance().reference.child("Posts").child("postID")
postsRef.child("postID").removeValue()
use
val postsRef = FirebaseDatabase.getInstance().reference.child("Posts").child(deletePost.text)
postsRef.removeValue()

Related

RecyclerView only displaying correct data when using breakpoints

I am trying to make my RecylerView display data from a database, however the recyclerView displays nothing, unless i walk through the code with breakpoints, in which case it displays as expected. In the EssayPlanDialogFragment i inisialised an empty arrayList to store the essay lists which then has essayParagrpahs added to it either if the dialogFragemnt is called from the previous essayFragment, in which case the fillIn() function is called to turn database data into paragraphs or if the add paragraph is pressed to add a new empty paragraph. The breakpoint that seem to make it work is on the var paragraphList = ArrayList() and triggers 8 times before displaying the data
RecyclerView Adapter
class EssayPlanAdapter(): RecyclerView.Adapter<EssayPlanAdapter.ViewHolder>() {
var paragraphList = ArrayList<essayParagraph>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var view = LayoutInflater.from(parent.context).inflate(R.layout.essay_paragraph_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
///code
}
override fun getItemCount(): Int {
return paragraphList.size
}
fun setData(paragraph: ArrayList<essayParagraph>) {
this.paragraphList = paragraph
notifyDataSetChanged()
}
//more code ViewHolder Class and code help with adding essayPlan to databse
}
EssayPlanDialogFragment
class essayPlayDialogFragment(questionId:Int,fromEssay:Int): DialogFragment() {
var paragraphs = ArrayList<essayParagraph>()
var fromEssay = fromEssay
lateinit var introduction: LinearLayout
lateinit var title:EditText
var questionId = questionId
override fun onCreateView(){
//code
}
override fun onViewCreated(view: View, #Nullable savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = EssayPlanAdapter()
title = view.findViewById(R.id.essayTitle)
introduction = view.findViewById(R.id.introduction)
val viewModle = ViewModelProvider(this).get(essayViewModle::class.java)
val paragraphRecycler: RecyclerView = view.findViewById(R.id.essayPlanRecycler)
val closeBtn: ImageButton = view.findViewById(R.id.closeButton)
val finishBtn:ImageButton = view.findViewById(R.id.finnishButton)
//if Dialog fragment opened from previousEssays prafment fromEssay == 1, if from makeNewEssayPragment == 0
if (fromEssay == 1){
val essay = viewModle.checkId(questionId) //returns essay with aprriate essayId
paragraphRecycler.adapter = adapter
paragraphRecycler.layoutManager = LinearLayoutManager(requireContext())
var tempEssays = fillIn(essay,introduction)
adapter.setData(tempEssay)
}
else{
paragraphRecycler.adapter = adapter
paragraphRecycler.layoutManager = LinearLayoutManager(requireContext())
adapter.setData(paragraphs)
}
val button: Button = view.findViewById(R.id.addParagraph)
button.setOnClickListener(){
paragraphs.add(essayParagraph("","","",""))
adapter.setData(paragraphs)
}
finishBtn.setOnClickListener {
//add essay to database
}
fun constructEssayPlanData(adapter: EssayPlanAdapter,intro:LinearLayout,ID:Int):EssayPlan{
//make essayPlan to be added to database
}
fun fillIn(essay:EssayPlan,intro: LinearLayout): ArrayList<essayParagraph>{
intro.lineOfThought.setText(essay.LOT.toString())
intro.relaventPlot.setText(essay.intro.toString())
title.setText("TestTest")
var topicSentences = essay.topicSentences.split("+").toMutableList()
topicSentences.removeAt(0)
var firstQuotes = essay.firstQuotes.split("+").toMutableList()
firstQuotes.removeAt(0)
var secondQuotes = essay.SecondQuotes.split("+").toMutableList()
secondQuotes.removeAt(0)
var thirdQuotes = essay.ThirdQuotes.split("+").toMutableList()
thirdQuotes.removeAt(0)
for(i in 0..(essay.numParagraph -1)){
var essayTemp = essayParagraph(topicSentences[i],firstQuotes[i],secondQuotes[i],thirdQuotes[i])
paragraphs.add(essayTemp)
}
return paragraphs
}
}
ViewModel
fun checkId(id:Int):EssayPlan{
var essay = EssayPlan(id,"","","","","","","",0)
viewModelScope.launch(Dispatchers.IO) {
essay = repository.check(id)
}
return essay
}
repository
fun check(id:Int):EssayPlan{
var essayPlans: EssayPlan = essayPlanDao.checkExist(id)
return essayPlans
}
DAO
#Query("SELECT * FROM plans WHERE id == :id LIMIT 1")
fun checkExist(id:Int):EssayPlan

Layout inflater is not inflating view

I feel that in this code my layout is not being attached.I verified by toast,log.d but nothing worked.Here this I am using for a recycler view view holder.Code is below
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.posts_layout,parent,false)
return ViewHolder(view)
}
and onBindViewHolder.I user log to check if this method is being used but,its not used
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
firebaseUser = FirebaseAuth.getInstance().currentUser!!
Log.d("binded", true.toString())
val post = mPost[position]
getPublisherInfo(holder.profileImage ,holder.userName , holder.userFullName ,post.getpublisher())
Glide.with(mContext).load(post.getpostId()).placeholder(R.drawable.image).into(holder.postImage)
}
I also checked if my list size id 0 for it to not come.For it use used log and it showed the list size 5 which is correct.This meant that my data is being retrieved from database.So it think that the my layout inflater is not working.The code for it is.
private fun readPosts() {
val postsRef = FirebaseDatabase.getInstance().reference.child("Posts")
postsRef.addValueEventListener(object : ValueEventListener{
#SuppressLint("NotifyDataSetChanged")
override fun onDataChange(snapshot: DataSnapshot) {
postList.clear()
for(snapshot in snapshot.children){
val post = snapshot.getValue(Post::class.java)
for (uid in (followingList as ArrayList<String>)) {
if (post!!.getpublisher().equals(uid)) {
postList.add(post)
}
Log.d("added", postList.size.toString())
Log.d("added", postList.toString())
postAdapter.notifyDataSetChanged()
}
}
}
override fun onCancelled(error: DatabaseError) {}
})
}
My entire adapter code is
package com.u_me_pro.free.Adapters
class PostAdapter(private val mContext: Context,private val mPost: List<Post>) :
RecyclerView.Adapter<PostAdapter.ViewHolder>() {
private lateinit var firebaseUser : FirebaseUser
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.posts_layout,parent,false)
Log.d("attached layout","true")
return ViewHolder(view)
}
class ViewHolder(#NonNull itemView: View) : RecyclerView.ViewHolder(itemView){
var description: TextView = itemView.findViewById(R.id.description)
var userName: TextView = itemView.findViewById(R.id.user_name_post)
var userFullName: TextView = itemView.findViewById(R.id.user_full_name_post)
var commentCount: TextView = itemView.findViewById(R.id.comment_count)
var likeCount: TextView = itemView.findViewById(R.id.love_count)
var profileImage: RoundedImageView = itemView.findViewById(R.id.user_profile_image_post)
var postImage: RoundedImageView = itemView.findViewById(R.id.post_image)
var like: CardView = itemView.findViewById(R.id.post_image_like)
var comment: CardView = itemView.findViewById(R.id.post_image_comment)
var save: CardView = itemView.findViewById(R.id.post_image_save)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
firebaseUser = FirebaseAuth.getInstance().currentUser!!
Log.d("binded", true.toString())
val post = mPost[position]
getPublisherInfo(holder.profileImage ,holder.userName , holder.userFullName ,post.getpublisher())
Glide.with(mContext).load(post.getpostId()).placeholder(R.drawable.image).into(holder.postImage)
}
override fun getItemCount(): Int {
return mPost.size
}
private fun getPublisherInfo(profileImage: RoundedImageView, userName: TextView, userFullName: TextView, publisherId: String) {
val usersRef = FirebaseDatabase.getInstance().reference.child("Users").child(publisherId)
Log.d("publisher id",publisherId)
usersRef.addValueEventListener(object :ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
val user = snapshot.getValue(User::class.java)
userName.text = user!!.getFullname()
userFullName.text = user.getFullname()
Glide.with(mContext).load(user.getImage()).placeholder(R.drawable.profile).into(profileImage)
}
}
override fun onCancelled(error: DatabaseError) {
Log.d(TAG, error.getMessage());
}
})
}
}
Please help me out soon.
Thanks!
You're updating the post list and notifying the adapter of a change but it doesn't appear that you're ever actually passing in the updated list to the adapter.
postAdapter.notifyDataSetChanged()
Won't do anything if the actual data in your adapter hasn't changed.
You should add a way to update your post list in the adapter such as
fun setPostData(posts: List<Post>) {
this.adapterPosts = posts
notifyDataSetChanged() // Either call this here or where you were before
}
This would also require you to create a new variable to hold the passed-in list
private var adapterPosts = mPosts

Issue with observe livedata in adapter - android

I'll give you some hint of my app , maybe help with my issue .
I have an Api an with retrofit I'll get this data . after that insert all data in roomdatabase .
In my main screen with a recyclerview I display all this product (data) .
Near each of this product I have a button to send product to the cart fragment .also have a value(textview) to save each button is pressed to show how many items gone to cart fragment .
I use a upsert(transaction) for insert or update the product to cart fragment .
and after that use a obvserver livedata to display the amount value of products that is send to cart .
First i need A way to implement the observe live data in my main screen instead of adapter / and also is my upsert query is correct ? sometimes when click on products button the other products value changes .
Here is my code :
Dao :
// this is for Maintable
#Query("SELECT * FROM main")
fun getalldata(): LiveData<List<Roomtable>>
// cart Table
#Query("SELECT * FROM Cart")
fun getAllFromCart(): LiveData<List<CartTable>>
#Query("SELECT * FROM Cart WHERE id = :int")
fun GetAllFromCart(int: Int): LiveData<List<CartTable>>
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertToCart(model: CartTable): Long
#Query("UPDATE cart SET amount = amount+1 WHERE id = :int")
fun updateCart(int: Int)
#Transaction
fun upsert(model: CartTable) {
val id = insertToCart(model)
if (id == -1L) {
model.id?.let {
updateCart(it)
}
MainAdapter :
class RecyclerAdapterMain(
private val product: List<Roomtable>,
val context: Context,
private val viewlifecyclerOwner: LifecycleOwner
) :
RecyclerView.Adapter<RecyclerAdapterMain.ViewHolder>() {
val viewModel: ViewModelRoom by lazy {
ViewModelProvider.AndroidViewModelFactory(Application()).create(ViewModelRoom::class.java)
}
inner class ViewHolder(itemview: View) :
RecyclerView.ViewHolder(itemview) {
val title: TextView = itemview.product_txt
val price: TextView = itemview.price_product
val imageproduct: ImageView = itemview.product_image
val btn_add_product: Button = itemview.btn_add_product
var amount_value: TextView = itemview.amount_value
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutview =
LayoutInflater.from(parent.context).inflate(R.layout.product_items, parent, false)
return ViewHolder(layoutview)
}
override fun getItemCount(): Int = product.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var products = product[position]
holder.title.text = products.title
holder.price.text = products.price
Picasso.get().load(products.image).into(holder.imageproduct)
holder.btn_add_product.setOnClickListener {
products.amount++
viewModel.upsert(
CartTable(
holder.adapterPosition,
products.title,
products.price,
products.image,
products.amount
)
)
viewModel.GetallFromCart(holder.adapterPosition).observe(viewlifecyclerOwner, Observer {
if (it != null) {
for (item in it) {
holder.amount_value.text = item.amount.toString()
}
}
})
}
Main Activity :
class HomeActivity : AppCompatActivity(){
val viewModel: ViewModelRoom by lazy {
ViewModelProvider(this).get(ViewModelRoom::class.java)
}
#RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.home_activity)
loadProduct()
#RequiresApi(Build.VERSION_CODES.M)
private fun loadProduct() {
swipeRefreshMain.isRefreshing = true
if (hasNetworkAvilable(applicationContext)) {
viewModel.setup()
viewModel.products.observe(this, Observer {
loadrecycler(it)
})
} else {
Toast.makeText(
applicationContext,
"برای بروز رسانی محصولات اینترنت خود را روشن کنید",
Toast.LENGTH_LONG
).show()
viewModel.getalldata().observe(this, Observer {
if (!it.isNullOrEmpty()) {
loadrecycler(it)
} else {
val builder = AlertDialog.Builder(this)
.setView(R.layout.customalertdialog)
.setPositiveButton("Ok", null)
.create()
.show()
val constraint = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val workmanager: WorkManager = WorkManager.getInstance(this)
val workRequest = OneTimeWorkRequest.Builder(UploadWorkerClass::class.java)
.setConstraints(constraint)
.build()
workmanager.enqueue(workRequest)
}
})
}
}
fun loadrecycler(product: List<Roomtable>) {
val swipeRefreshLayout: SwipeRefreshLayout = findViewById(R.id.swipeRefreshMain)
val recycler: RecyclerView = findViewById(R.id.recycler_main)
recycler.apply {
layoutManager = GridLayoutManager(this#HomeActivity, 2)
adapter = RecyclerAdapterMain(
product, this#HomeActivity, this#HomeActivity )
Handler(Looper.getMainLooper()).postDelayed({
swipeRefreshLayout.isRefreshing = false
}, randomInRange(1, 3) * 1000.toLong())
}
}
}

How can I pass the arrayList from adapter to new activity with intent in kotlin, android app?

I am a new about making app. I want to pass the data from adapter to new activity with intent. I want to transfer PastNotesActivity, but it does not working.Because oldTitleName shows me the error: found String, Required editable. How can ı fix it ?
class NoteAdapter(private var titleText: ArrayList<String>, private var image: ArrayList<String>) : RecyclerView.Adapter<NoteAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemTitle : TextView = itemView.findViewById(R.id.recyclerTitleText)
val itemImage : ImageView = itemView.findViewById(R.id.recyclerImage)
init {
itemView.setOnClickListener { v: View ->
// Toast.makeText(itemView.context,"You clicked on item # ${position + 1}", Toast.LENGTH_SHORT).show()
val intent = Intent(itemView.context, PastNotesActivity::class.java)
intent.putExtra("oldTitle", titleText[position])
itemView.context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_row, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemTitle.text = titleText[position]
Picasso.get().load(image[position]).into(holder.itemImage)
}
override fun getItemCount(): Int {
return titleText.size
}
}
This is PastNotesActivity, oldTitleName shows me the error: found String, Required editable. How can ı fix it ?
class PastNotesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_past_notes)
val intent = intent
val oldTitleName = intent.getStringExtra("oldTitle")
pastTitleText.text = oldTitleName
val navBarTitle = intent.getStringExtra("oldTitle")
supportActionBar?.title = navBarTitle
}
}
Lets say that you are passing the text of an item from your recyclerView to the textView of a desired activity.
Code this...
val intent = Intent(itemView.context, PastNotesActivity::class.java)
intent.putExtra("sampledText", "test123")
And code this in your desired activity...
val textFromIntent = intent.getStringExtra("sampledText")
textView.text = textFromintent

Get clicked item in recyclerview adapter

I want to create an android app with Kotlin. In this app, i use swagger also to get all the web service in a file.
I want to create an interface, the description is as follows:
A RecyclerView horizontal that contains all the list of categories
comes from a web service apiMobileProductCategoriesGetAllPost.
after that, when i click on a which category, a RecyclerView(Grid)
appear that contains all the product by category id.
I want to know how can i get the category id when i click on item,and how to use it in the activity
The following the RecyclerView category adapter:
class CategoryAdapter(private val categories: Array<ProductCategoryData>) :
RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {
private var onItemClickListener: OnItemClickListener? = null
override fun onClick(v: View?) {
if (v != null) {
onItemClickListener?.onItemClick(v, ProductCategoryData())
}
}
fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
this.onItemClickListener = onItemClickListener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.category_item, parent, false)
view.setOnClickListener(this)
return ViewHolder(view)
}
override fun getItemCount() = categories.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val itemCategory: ProductCategoryData = categories[position]
holder.categoryId.text = itemCategory.id.toString()
println(holder.categoryId.text)
println(itemCategory.name?.get("En").toString())
holder.categoryName.text = itemCategory.name?.get("En").toString()
println(itemCategory.id)
if (itemCategory.logo != null) {
Picasso.get()
.load("..../T/${itemCategory.logo}")
.into(holder.categoryImage, object : com.squareup.picasso.Callback {
override fun onError(e: Exception?) {
holder.categoryImage.setImageResource(R.drawable.homecraftdefault)
}
override fun onSuccess() {
Picasso.get().load("....T/${itemCategory.logo}")
.into(holder.categoryImage)
}
})
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClick(holder.itemView,itemCategory)
}
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val categoryName: TextView = itemView.categoryName
val categoryImage: ImageView = itemView.categoryImage
val categoryId: TextView = itemView.categoryId
override fun onClick(v: View?) {
if (v != null) {
onItemClickListener?.onItemClick(v, ProductCategoryData())
}
}
}
interface OnItemClickListener {
fun onItemClick(view : View, viewModel:ProductCategoryData)
}
}
The following code is relative to the activity:
class CategoryByProduct : AppCompatActivity(), CategoryAdapter.OnItemClickListener {
override fun onItemClick(view: View, viewModel: ProductCategoryData) {
var params = "CategoryProductID";"5cc057458c4d9823743736d2"
println(viewModel.id)
val products = mobileApi!!.apiMobileProductsGetAllPost(params, 0, 50, "", "")
recyclerViewProductByCategory.apply {
recyclerViewProductByCategory.layoutManager = GridLayoutManager(this#CategoryByProduct, 2)
recyclerViewProductByCategory.adapter = ProductAdapter(products)
} }
var mobileApi: MobileApi? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.list_product_by_category)
mobileApi = MobileApi()
val params = HashMap<String, String>()
GlobalScope.launch(Dispatchers.IO) {
val categories = mobileApi!!.apiMobileProductCategoriesGetAllPost(params, 0, 50, "", "")
withContext(Dispatchers.Main) {
recyclerViewCategories.apply {
recyclerViewCategories.layoutManager =
LinearLayoutManager(this#CategoryByProduct, OrientationHelper.HORIZONTAL, false)
recyclerViewCategories.adapter = CategoryAdapter(categories)
}
}
}
}
}
First of all , never put your onclick in onBindViewHolder That's not a good practice, after that i think you need to get the ID of the category i will give you simple example in all of the Adapter Class
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.newslist , 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.newscardview.setOnClickListener {
//do it here
Toast.makeText(this,currentnews!!.id,Toast.LENGTH_SHORT).show()
}
//the end of the init
}
//getting data from model and bind it into View
fun setData(news: NewsModel?, position: Int) {
news?.let {
itemView.newsid.text = news.id
itemView.newstitle.text = news.title
itemView.body.text = news.body
itemView.txtdate.text = news.ndate
}
this.currentnews = news
this.currentPosition = position
}
}
}
In this example you will get the news ID when you click newscardview, i hope to understand it
In your Activity
put this code in onCreate
//set up the recycleview
mRecyclerView.setHasFixedSize (true)
mRecyclerView. layoutManager = LinearLayoutManager(this)
mRecyclerView is my RecycleView
also call your Adapter class in anywhere you want
//adapter
val adapter = NewsAdapter (this,arrayList)
adapter.notifyDataSetChanged()
mRecyclerView.adapter = adapter
you get the position of the category inside a viewholder by calling adapterPosition and with this you can get the category from your list you provide to your adapter in the constructor (categories[adapterPosition])
In your case it is very simple.Try these:-
holder.tv_broadcast_title.text=broadList[position].name
where broadlist is my array list created in the adapter itself.In this list the json data is getting stored from api.
internal var broadList = ArrayList<Model>()
and .name is the name of key to fetch name from json data.
holder.categoryName.text = itemCategory.name?.get("En").toString()
in your case do something like this:-
itemCategory[position].name
To get data from adapter to activity, you can make an interface in the adapter or globally and from the activity you can pass that interface in adapter's constructor and use that to get data. I am giving you an example.
interface ProductCategoryListner {
fun getProductCategory(viewModel:ProductCategoryData)
}
Not in adapter's constructor add this interface.
class CategoryAdapter(private val categories: Array<ProductCategoryData>,private val productCategoryListner: ProductCategoryListner):
RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {
Now you can use this to pass data in the activity when you click on view.
productCategoryListner.getProductCategory(categories[adapterPosition])

Categories

Resources