Trying to open another activity in recycles view using onclick - android

Trying to get a button to open another activity in android studio using kotlin. I am user a recycles view to do so. I have view card and want to edit the data in the card so I am user onClick to get the page to respond but that does seem to work I tried researching it but nothing come up that I can make sense of. Here is the code.
Thank you for all your help I appreciate it
This is the adapter class:
```class EventAdapter(var mListener: onItemClickListener, var context: Context, val items: ArrayList<EventModelk>):
RecyclerView.Adapter<EventAdapter.ViewHolder>() {
interface onItemClickListener {
fun onItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemview = LayoutInflater.from(context).inflate(
R.layout.eventitems,
parent,
false,
)
return ViewHolder(itemview, mListener)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.setEmail.text = item.eEmail
holder.setNotes.text = item.nNotes
holder.setData.text = item.dDate
holder.setTime.text = item.tTime
if (item.repeat == 1) {
holder.setReap.isChecked = true
// holder.setReap.text = item.repeat.toString()
}
if (position % 2 == 0) {
holder.main.setBackgroundColor(
ContextCompat.getColor(
context,
R.color.colorLightGray
)
)
} else {
holder.main.setBackgroundColor(ContextCompat.getColor(context, R.color.colorWhite))
}
holder.pushimg.setOnClickListener {
if (context is UpdateDataInfo) {
(context as UpdateDataInfo).updateEvent(item)
}
}
// interface onItemClickListener{
// fun onItemClick(position: Int)
}
override fun getItemCount(): Int {
return items.size
}
class ViewHolder(view: View,onItemClickListener: onItemClickListener): RecyclerView.ViewHolder(view),onItemClickListener {
val main: CardView = view.IIMain
val setData: TextView = view.set_date
val setTime: TextView = view.set_time
val setEmail: TextView = view.Tv_email
val setNotes: TextView = view.set_note
val setReap: CheckBox =view.is_repeat
val pushimg: ImageView = view.img_edit
val onItemClickListener = onItemClickListener
override fun onItemClick(position: Int) {
onItemClickListener.onItemClick(absoluteAdapterPosition)
}
}
}```
This is my code for getting the click to go to another activity:
class CurrentSch : AppCompatActivity(), EventAdapter.onItemClickListener {
//private var change =imageView2?.isClickable
var STORAGE_LOCAL =true
val eventlist = ArrayList<EventModelk>()
#RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.currentsch)
btnNewApp2.setOnClickListener {
val intent = Intent(this, NewPlan::class.java)
startActivity(intent)
}
seeAllEventInPlan()
}
//private var change =imageView2?.isClickable
private fun getEventist(): ArrayList<EventModelk>{
val eventdatabase = EventDatabasek(this)
return eventdatabase.veiwEvent()
}
fun seeAllEventInPlan() = if(getEventist().size >0){
ryc_eventLists.visibility = View.VISIBLE
viewnotview.visibility = View.GONE
ryc_eventLists.layoutManager = LinearLayoutManager(this)
val eventAdapter = EventAdapter(this,this, getEventist())
ryc_eventLists.adapter = eventAdapter
}else{
ryc_eventLists.visibility = View.GONE
viewnotview.visibility = View.VISIBLE
}
override fun onItemClick(position: Int) {
val item = eventlist[position]
img_edit.setOnClickListener {
val intent = Intent(this, UpdateDataInfo::class.java)
intent.putExtra("Events", position)
startActivity(intent)
}
}
}

Inside the onBindViewHolder function, simply call mListener.onItemClick(position) for example if you wanted to open another Activity on click of setData, then you can write below code in onBindViewHolder
holder.setData.setOnClickListener { mListener.onItemClick(position) }

according to your above code , you have made callbacks where you calling thee adapter you will get callback there and you will open a activity there .. .. but you can simple open your new activity from adapter like this ..
holder.itemView.setOnClickListener(View.OnClickListener {
val intent = Intent (context,SomeActivity::class.java)
context.startactivity(intent)
})

Related

Kotlin] I want to send some data from One class to Other class by using Intent

I just want to say sorry to my English skill
I've studied the Android Studio and Kotlin these days.
but I'd got a problem on RecyclerViewer and Adapter, for Intent method
work flow chart
this image, this is what i want to do
so i coded the three classes
ShoppingAppActivity.kt, MyAdapter.kt, CartActivity.kt
At ShoppingAppActivity, If I click the itemId ( in the Red box texts)
I make it move to other context(CartActivity)
ShoppingAppActivity working
if i clicked the red box then
cartStatus
go to cart Activity
it worked but already I said, I just want to send only send itemID
covert to String (i will use toString())
SO i tried to use Intent method in ShoppingAppActivity.kt
///PROBLEM PART
adapter?.setOnItemClickListener{
val nextIntent = Intent(this, CartActivity::class.java)
//nextIntent.putExtra("itemID", )
startActivity(nextIntent)
}
///PROBLEM PART
like this but the problem is I don't know what am i have to put the parameter in
nextIntent.putExtra("itemID", )
what should i do?
I think, I should fix MyAdaptor.kt or ShopingAppActivity.kt for this problem.
But in my knowledge, this is my limit. :-(
below
Full Codes of ShoppingAppActivity.kt, MyAdapter.kt, CartActivity.kt
ShoppingAppActivity.kt
class ShoppingAppActivity : AppCompatActivity() {
lateinit var binding: ActivityShoppingAppBinding
private var adapter: MyAdapter? = null
private val db : FirebaseFirestore = Firebase.firestore
private val itemsCollectionRef = db.collection("items")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityShoppingAppBinding.inflate(layoutInflater)
setContentView(binding.root)
updateList()
binding.recyclerViewItems.layoutManager = LinearLayoutManager(this)
adapter = MyAdapter(this, emptyList())
binding.recyclerViewItems.adapter = adapter
///PROBLEM PART
adapter?.setOnItemClickListener{
val nextIntent = Intent(this, CartActivity::class.java)
//nextIntent.putExtra("itemID", )
startActivity(nextIntent)
}
///PROBLEM PART
}
private fun updateList() {
itemsCollectionRef.get().addOnSuccessListener {
val items = mutableListOf<Item>()
for (doc in it) {
items.add(Item(doc))
}
adapter?.updateList(items)
}
}
}
MyAdapter.kt
data class Item(val id: String, val name: String, val price: Int, val cart: Boolean) {
constructor(doc: QueryDocumentSnapshot) :
this(doc.id, doc["name"].toString(), doc["price"].toString().toIntOrNull() ?: 0, doc["cart"].toString().toBoolean() ?: false)
constructor(key: String, map: Map<*, *>) :
this(key, map["name"].toString(), map["price"].toString().toIntOrNull() ?: 0, map["cart"].toString().toBoolean() ?: false)
}
class MyViewHolder(val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root)
class MyAdapter(private val context: Context, private var items: List<Item>)
: RecyclerView.Adapter<MyViewHolder>() {
fun interface OnItemClickListener {
fun onItemClick(student_id: String)
}
private var itemClickListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
itemClickListener = listener
}
fun updateList(newList: List<Item>) {
items = newList
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding: ItemBinding = ItemBinding.inflate(inflater, parent, false)
return MyViewHolder(binding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = items[position]
val itemID : String
holder.binding.textID.text = item.id
holder.binding.textName.text = item.name
if(item.cart)
{
holder.binding.textCart.text = "in Cart"
}
else
{
holder.binding.textCart.text = ""
}
holder.binding.textID.setOnClickListener {
AlertDialog.Builder(context).setMessage("You clicked ${item.id}.").show()
itemClickListener?.onItemClick(item.id)
}
holder.binding.textName.setOnClickListener {
//AlertDialog.Builder(context).setMessage("You clicked ${student.name}.").show()
itemClickListener?.onItemClick(item.id)
}
//return item.id.toString()
}
override fun getItemCount() = items.size
}
CartActivity.kt
class CartActivity : AppCompatActivity() {
lateinit var binding: ActivityCartBinding
private val db: FirebaseFirestore = Firebase.firestore
private val itemsCollectionRef = db.collection("items")
private var adapter: MyAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCartBinding.inflate(layoutInflater)
setContentView(binding.root)
updateList()
//binding.recyclerViewItems.layoutManager = LinearLayoutManager(this)
//adapter = MyAdapter(this, emptyList())
//binding.recyclerViewItems.adapter = adapter
binding.changeCartStatus.setOnClickListener{
//change the button's text if the itemID is corrected
//if(){
// binding.changeCartStatus.text = ""
//}
}
}
private fun updateList() {
itemsCollectionRef.get().addOnSuccessListener {
val items = mutableListOf<Item>()
for (doc in it) {
items.add(Item(doc))
}
adapter?.updateList(items)
}
}
}
You just need to implement listener to your activity
class ShoppingAppActivity : AppCompatActivity() ,MyAdapter.OnItemClickListener {
In oncreate add below line after adapter
adapter?.setOnItemClickListener(this)
Then override its method
override fun onItemClick(id: String){
val nextIntent = Intent(this, CartActivity::class.java)
nextIntent.putExtra("itemID",id )
startActivity(nextIntent)
}

I try to pass the image from Adapter to the other activity with intent in Kotlin, Android, but ıt does not display. What should I do?

Hi everyone ı am a new about android kotlin, I just try to pass the image from adapter to the other activity but it does not display. I used the intent code. What should I do ? I shared my adapter and the other activity code so you can see how ı used the intent code,
my adapter;
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 ->
val intent = Intent(itemView.context, PastNotesActivity::class.java)
intent.putExtra("oldTitle", titleText[position])
intent.putExtra("oldImage", image[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]).resize(150,150).into(holder.itemImage)
}
override fun getItemCount(): Int {
return titleText.size
}
}
The other activity code,
class PastNotesActivity : AppCompatActivity() {
var selectedPicture: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_past_notes)
val intent = intent
val oldTitleName = intent.getStringExtra("oldTitle")
val oTitle = findViewById<TextView>(R.id.pastTitleText)
oTitle.text = oldTitleName
val oldImageView:Int = intent.getIntExtra("oldImage", 0)
val imageView = findViewById<ImageView>(R.id.pastImage)
imageView.setImageResource(oldImageView)
}
}
Inside your PastNotesActivity you are extracting IntExtra but you sent StringExtra.
Change your code from
val oldImageView:Int = intent.getIntExtra("oldImage", 0)
To
val oldImageView:String = intent.getStringExtra("oldImage", "")
Then load the image using Picasso as you did in your onBindViewHolder.

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])

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()

Button Checklist all on Recyclerview does not work

I have recyclerview with checkbox and I want to checklist all the data using button. I have trying this tutorial, but when i click the button, the log is call the isSelectedAll function but can't make the checkbox checked. what wrong with my code?
this is my adapter code
var isSelectedAll = false
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListApproveDeatilViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.activity_list_approve_row, parent, false)
return ListApproveDeatilViewHolder(itemView)
}
private lateinit var mSelectedItemsIds: SparseBooleanArray
fun selectAll() {
Log.e("onClickSelectAll", "yes")
isSelectedAll = true
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: ListApproveDeatilViewHolder, position: Int) {
val approve = dataSet!![position]
holder.soal.text = approve.title
holder.kategori.text = approve.kategori
if (!isSelectedAll){
holder.checkBox.setChecked(false)
} else {
holder.checkBox.setChecked(true)
}
}
and this is my activity code
override fun onCreate(savedInstanceState: Bundle?) {
private var adapter: ListApproveDetailAdapter? = null
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_approve)
ButterKnife.bind(this)
getData()
// this is my button onclick code
select.setOnClickListener(){
if (select.getText().toString().equals("Select all")){
Toast.makeText(this, "" + select.getText().toString(), Toast.LENGTH_SHORT).show()
adapter?.selectAll()
select.setText("Deselect all")
} else {
Toast.makeText(this, "" + select.getText().toString(), Toast.LENGTH_SHORT).show()
select.setText("Select all")
}
}
}
//this is for get my data for the recyclerview
fun getData() {
val created_by = intent.getStringExtra(ID_SA)
val tgl_supervisi = intent.getStringExtra(TGL_SURVEY)
val no_dlr = intent.getStringExtra(NO_DLR)
API.getListApproveDetail(created_by, tgl_supervisi, no_dlr).enqueue(object : Callback<ArrayList<ListApprove>> {
override fun onResponse(call: Call<ArrayList<ListApprove>>, response: Response<ArrayList<ListApprove>>) {
if (response.code() == 200) {
tempDatas = response.body()
Log.i("Data Index History", "" + tempDatas)
recyclerviewApprove?.setHasFixedSize(true)
recyclerviewApprove?.layoutManager = LinearLayoutManager(this#ListApproveActivity)
recyclerviewApprove?.adapter = ListApproveDetailAdapter(tempDatas)
adapter?.notifyDataSetChanged()
} else {
Toast.makeText(this#ListApproveActivity, "Error", Toast.LENGTH_LONG).show()
}
swipeRefreshLayout.isRefreshing = false
}
override fun onFailure(call: Call<ArrayList<ListApprove>>, t: Throwable) {
Toast.makeText(this#ListApproveActivity, "Error", Toast.LENGTH_SHORT).show()
swipeRefreshLayout.isRefreshing = false
}
})
}
thankyou for any help :)
I am posting the answer with implementation of demo project. I haven't modified your code but as per your requirement i have done this.
MainActivity class:
class MainActivity : AppCompatActivity() {
var selectAll: Boolean = false;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView) as RecyclerView
val btnSelectAll = findViewById<Button>(R.id.btnSelectAll) as Button
//adding a layoutmanager
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
//crating an arraylist to store users using the data class user
val users = ArrayList<User>()
//adding some dummy data to the list
users.add(User("Piyush", "Ranchi"))
users.add(User("Mehul", "Chennai"))
users.add(User("Karan", "TamilNadu"))
users.add(User("Bela", "Kolkata"))
//creating our adapter
val adapter = CustomAdapter(users, selectAll)
//now adding the adapter to recyclerview
recyclerView.adapter = adapter
btnSelectAll.setOnClickListener {
if (!selectAll) {
selectAll = true
} else {
selectAll = false
}
adapter?.selectAllCheckBoxes(selectAll)
}
}
}
User class:
data class User(val name: String, val address: String)
Adapter class:
class CustomAdapter(val userList: ArrayList<User>, val selectAll: Boolean) :
RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
var selectAllA = selectAll;
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
holder.textViewName.text = userList[position].name;
if (!selectAllA){
holder.checkBox.setChecked(false)
} else {
holder.checkBox.setChecked(true)
}
}
//this method is giving the size of the list
override fun getItemCount(): Int {
return userList.size
}
//the class is hodling the list view
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textViewName = itemView.findViewById(R.id.textViewUsername) as TextView
val checkBox = itemView.findViewById(R.id.checkbox) as CheckBox
}
fun selectAllCheckBoxes(selectAll: Boolean) {
selectAllA = selectAll
notifyDataSetChanged()
}
}
As i already mentioned in comments you are using two different adapter instance .
Now i see you have declared adapter globally .
Just modify your code as follows and make sure response.body() have data int it :
if (response.code() == 200) {
tempDatas = response.body()
Log.i("Data Index History", "" + tempDatas)
recyclerviewApprove?.setHasFixedSize(true)
recyclerviewApprove?.layoutManager = LinearLayoutManager(this#ListApproveActivity)
adapter = ListApproveDetailAdapter(tempDatas)
recyclerviewApprove?.adapter=adapter
} else {
Toast.makeText(this#ListApproveActivity, "Error", Toast.LENGTH_LONG).show()
}
Add one variable in model class.
like var isSelect : Boolean
In your selectAll() method update adpter list and notify adapter.
Edit:
in the adapter class.
if (approve.isSelect){
holder.checkBox.setChecked(true)
} else {
holder.checkBox.setChecked(false)
}
Hope this may help you.
OR
If you are using AndroidX then use should use one recyclerview features.
androidx.recyclerview.selection
A RecyclerView addon library providing support for item selection. The
library provides support for both touch and mouse driven selection.
Developers retain control over the visual representation, and the
policies controlling selection behavior (like which items are eligible
for selection, and how many items can be selected.)
Reference from here

Categories

Resources