error in using Gson Api with recyclerview? - android

hello guys I am using a gson api with a Recyclerview and I got this error with the adapter and it says that the
expression 'myAdapter' of type 'myAdapter' cannot be invoked as a function. the function 'invoked' is not found
and when I run the code without the data it gives me this error:
lateinit property myAdapter has not been initialized
my activities and classes
private val datalist: MutableList<Sura> = mutableListOf()
private lateinit var myAdapter: MyAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quran_a_p_i)
myAdapter = myAdapter(datalist) // here is the error
apiQuranRecyclerView.layoutManager = LinearLayoutManager(this)
apiQuranRecyclerView.addItemDecoration(DividerItemDecoration(this, OrientationHelper.VERTICAL))
apiQuranRecyclerView.adapter = myAdapter
AndroidNetworking.initialize(this)
AndroidNetworking.get("http://api.islamhouse.com/v1/mykey/quran/get-category/462298/ar/json/")
.build()
.getAsObject(Surasnames::class.java, object : ParsedRequestListener<Surasnames>{
override fun onResponse(response: Surasnames) {
datalist.addAll(response.suras)
myAdapter.notifyDataSetChanged()
}
override fun onError(anError: ANError?) {
}
})
}
my Adapter
class MyAdapter (private val datalist: MutableList<Sura>): RecyclerView.Adapter<myHolder>() {
private lateinit var context: Context
override fun onCreateViewHolder(parent: ViewGroup, p1: Int): myHolder {
context = parent.context
return myHolder(LayoutInflater.from(context).inflate(R.layout.api_quran_view, parent, false))
}
override fun getItemCount(): Int = datalist.size
override fun onBindViewHolder(holder: myHolder, position: Int) {
val data = datalist[position]
val apisuraname = holder.itemView.apiSuraNames
val surasnames = "${data.id} ${data.title}"
apisuraname.text = surasnames
holder.itemView.setOnClickListener {
Toast.makeText(context, surasnames, Toast.LENGTH_SHORT).show()
}
}
my Holder
class myHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
my Models
data class Sura(
#SerializedName("add_date")
val addDate: Int,
#SerializedName("api_url")
val apiUrl: String,
#SerializedName("id")
val id: Int,
#SerializedName("title")
val title: String,
#SerializedName("type")
val type: String
)
the second one
data class Surasnames(
#SerializedName("add_date")
val addDate: Int,
#SerializedName("description")
val description: String,
#SerializedName("id")
val id: Int,
#SerializedName("locales")
val locales: List<Any>,
#SerializedName("suras")
val suras: List<Sura>,
#SerializedName("title")
val title: String)
thanks in advance

You need to call the constructor. Change the line
myAdapter = myAdapter(datalist)
to
myAdapter = MyAdapter(datalist)

Related

how to implement search viewmodel and show it in recyclerview in kotlin

I am developing tvshows app where I am implementing following logic user search tvshows and filtered result has to show in recyclerview but I want to implement filtering functionality in viewmodel
how can I achieve that
below interface class
interface ApiInterface {
#GET("search/shows")
suspend fun searchShows( #Query("q") query: String): Call<TvMazeResponse>
}
below TvRepository.kt
class TvRepository(private val apiInterface: ApiInterface) {
suspend fun getShows() = apiInterface.searchShows("")
}
below adapter class
class TvAdapter : RecyclerView.Adapter<TvAdapter.ViewHolder>(), Filterable {
lateinit var tvMazeList: MutableList<TvMazeResponse>
lateinit var filterResult: ArrayList<TvMazeResponse>
override fun getItemCount(): Int =
filterResult.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.tv_item, parent,
false
)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(filterResult[position])
}
fun addData(list: List<TvMazeResponse>) {
tvMazeList = list as MutableList<TvMazeResponse>
filterResult = tvMazeList as ArrayList<TvMazeResponse>
notifyDataSetChanged()
}
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val charString = constraint?.toString() ?: ""
if (charString.isEmpty()) filterResult =
tvMazeList as ArrayList<TvMazeResponse> else {
val filteredList = ArrayList<TvMazeResponse>()
tvMazeList
.filter {
(it.name.contains(constraint!!)) or
(it.language.contains(constraint))
}
.forEach { filteredList.add(it) }
filterResult = filteredList
}
return FilterResults().apply { values = filterResult }
}
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
filterResult = if (results?.values == null)
ArrayList()
else
results.values as ArrayList<TvMazeResponse>
notifyDataSetChanged()
}
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(result: TvMazeResponse) {
with(itemView) {
Picasso.get().load(result.image.medium).into(imageView)
}
}
}
}
below Constants.kt
object Constants {
const val BASE_URL = "https://api.tvmaze.com/"
}
below TvMazeResponse.kt
data class TvMazeResponse(
#SerializedName("averageRuntime")
val averageRuntime: Int,
#SerializedName("dvdCountry")
val dvdCountry: Any,
#SerializedName("externals")
val externals: Externals,
#SerializedName("genres")
val genres: List<String>,
#SerializedName("id")
val id: Int,
#SerializedName("image")
val image: Image,
#SerializedName("language")
val language: String,
#SerializedName("_links")
val links: Links,
#SerializedName("name")
val name: String,
#SerializedName("network")
val network: Network,
#SerializedName("officialSite")
val officialSite: String,
#SerializedName("premiered")
val premiered: String,
#SerializedName("rating")
val rating: Rating,
#SerializedName("runtime")
val runtime: Int,
#SerializedName("schedule")
val schedule: Schedule,
#SerializedName("status")
val status: String,
#SerializedName("summary")
val summary: String,
#SerializedName("type")
val type: String,
#SerializedName("updated")
val updated: Int,
#SerializedName("url")
val url: String,
#SerializedName("webChannel")
val webChannel: Any,
#SerializedName("weight")
val weight: Int
)
below TvViewModel.kt
class TvViewModel(apiInterface: ApiInterface) : ViewModel() {
}
I want to implement filter and search function in viewmodel how can I achieve that any help and tips greatly appreciated
In TvRepository change the getShows function to
suspend fun getShows(searchString:String) = apiInterface.searchShows(searchString)
Then in the ViewModel change the constructor to get an instance of the TVRepository and call API as shown below
class TvViewModel( tvRepository: TvRepository) : ViewModel() {
fun getShows(searchParameter:String){
viewModelScope.launch(Dispatchers.IO){
val response= tvRepository.getShows().awaitResponse()
if(response.isSuccessful{
//api success you can get result from response.body
}
else{
//api failed
}
}
}
}

Retfrofit on response gets java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
Good day, I'm using Retrofit for the first time and I can't seem to get it to work. working on an app that get crypto currency rates in local currencies, here is the api [link], JSON format
Here are my models for News
data class News(
#field:SerializedName("totalResults")
val totalResults: Int,
#field:SerializedName("articles")
val articles: List<NewsArticle>?=null,
#field:SerializedName("status")
val status: String)
My model calss for NewsArticles:
data class NewsArticle(
#field:SerializedName("urlToImage")
val urlToImage: String? = null,
#field:SerializedName("description")
val description: String? = null,
#field:SerializedName("title")
val title: String? = null,
#field:SerializedName("url")
val url: String? = null,)
My interface:
const val BASE_URL = "https://saurav.tech/NewsAPI/"
interface NewsApiService {
#GET("top-headlines.json")
fun getNews(
#Query("category") category: String,
#Query("country_code") country_code: String
): Call<News>}
object NewsApi{
val newsInstance:NewsApiService
init {
val retrofit=Retrofit.Builder()
.baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
.build()
newsInstance=retrofit.create(NewsApiService::class.java)
}
}
My MainActivity class
class MainActivity : AppCompatActivity() {
private lateinit var adapter: NewsAdapter
//var totalResult=1
private var article = mutableListOf<NewsArticle>()
lateinit var refreshLayout: SwipeRefreshLayout
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerViewNews)
refreshLayout = findViewById(R.id.refreshLayout)
adapter = NewsAdapter(this#MainActivity, article)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this#MainActivity)
fetchNews()
}
private fun fetchNews() {
val news = NewsApi.newsInstance.getNews("technology", "in")
news.enqueue(object : Callback<News> {
override fun onResponse(call: Call<News>, response: Response<News>) {
val news = response.body()
article.addAll(news!!.articles)
}
override fun onFailure(call: Call<News>, t: Throwable) {
Toast.makeText(applicationContext, t.message, Toast.LENGTH_SHORT).show()
}
})
}
}
My AdapterClass:
class NewsAdapter(val context: Context, val newsArticles: MutableList<NewsArticle>) :
RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.news_items, parent, false)
return NewsViewHolder(view)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
val article = newsArticles[position]
holder.title.text = article.title
holder.description.text = article.description
Glide.with(holder.itemView.context).load(article.urlToImage).into(holder.image)
}
override fun getItemCount() = newsArticles.size
class NewsViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val title = view.findViewById<TextView>(R.id.titleText)!!
val description = view.findViewById<TextView>(R.id.descriptionText)!!
val image = view.findViewById<ImageView>(R.id.NewsImage)!!
}
}
When I run the code and check my log I get this error:
java.lang.NullPointerException
at com.ashish.technews.uis.MainActivity$fetchNews$1.onResponse(MainActivity.kt:44)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$hVGjmafRi6VitDIrPNdoFizVAdk.run(lambda)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
What's Happening?
Article List in the response is not coming and it is not being handled properly.
Solution
Replace this: article.addAll(news!!.articles)
With this: news?.let { article.addAll(it.articles) }

Kotlin adapter remove item

I'm trying to have item removed from my list but I get following error
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline fun <T> MutableCollection<out TypeVariable(T)>.remove(element: TypeVariable(T)): Boolean defined in kotlin.collections
public inline fun <T> MutableList<TypeVariable(T)>.remove(index: Int): TypeVariable(T) defined in kotlin.collections
public inline fun <K, V> MutableMap<out TypeVariable(K), TypeVariable(V)>.remove(key: TypeVariable(K)): TypeVariable(V)? defined in kotlin.collections
Code
class EducationsAdapter(val context: Context?, private var educationList: MyEducations) : RecyclerView.Adapter<EducationsAdapter.EducationsAdapterViewHolder>() {
override fun getItemCount()= educationList.data.size
// other functions...
override fun onBindViewHolder(holder: EducationsAdapter.EducationsAdapterViewHolder, position: Int)
{
holder.educationDelete.setOnClickListener {
deleteMyEducations(currentItem.id, position)
}
}
//delete
private fun deleteMyEducations(id: String, position: Int) {
// ".remove" is returning error above
educationList.remove(position)
notifyDataSetChanged()
}
}
Any suggestions?
Update
My MyEducations class (rendering data coming from server)
data class MyEducations(
val data: List<Education>,
val message: String
) { }
data class Education(
val id: String,
val start: String,
val end: String,
val title: String,
val body: String,
val user: User,
val created_at: String,
val updated_at: String,
) {}
Update 2
I've made following changes
// add
val list = mutableListOf<MyEducations>()
private fun deleteMyEducations(id: String, position: Int) {
//changed to
list.remove(educationList.data[position])
notifyDataSetChanged()
}
What it does is make flashing remove of the item (meaning: for less than a second my item removes and back again to the list)!
Solved
//changed my list to `ArrayList<Education>`
class EducationsAdapter(val context: Context?, private var educationList: ArrayList<Education>) : RecyclerView.Adapter<EducationsAdapter.EducationsAdapterViewHolder>() {
// and my delete code to
private fun deleteMyEducations(id: String, position: Int) {
educationList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, educationList.size)
notifyDataSetChanged()
}
}
Also I had to change my class to ArrayList as well
data class MyEducations(
val data: ArrayList<Education>,
val message: String
) { }
Try With
val list = mutableListOf<MyEducations>()
private fun deleteMyEducations(id: String, position: Int) {
list.removeAt(position)
notifyDataSetChanged()
}
You should be able to delete with something like:
class EducationListAdapter: RecyclerView.Adapter<EducationListAdapter.EducationViewHolder>() {
var educationList: MutableList<Education> = mutableListOf()
override fun onBindViewHolder(holder: EducationViewHolder, position: Int) {
val current = educationList.toList()
holder.view.setOnClickListener {
educationList.remove(current[position])
notifyItemRemoved(position)
}
}
}

How to send data From One RecyclerView Item to load another RecyclerView using Nested JSON using Kotlin

I have two activity and each activity has recyclerview, I have nested json.I want when user tap first activity recyclerview then they goes to next activity and show the recyclerview.Better understanding please follow the json link and code.
Json Link
: https://run.mocky.io/v3/8c3f6be2-a53f-47da-838c-72e603af844d
CropData.kt
data class CropData(
#SerializedName("cropImage")
val cropImage: String,
#SerializedName("cropName")
val cropName: String,
#SerializedName("cropTime")
val cropTime: String,
#SerializedName("cropDetails")
val cropDetails: String,
#SerializedName("cropProcess")
val cropProcess: String,
#SerializedName("cropType")
val cropType: String,
#SerializedName("cropFertilizer")
val cropFertilizer: List<CropFertilizer>
)
CropFertilizer.kt
data class CropFertilizer(
#SerializedName("fertilizerName")
val fertilizerName: String,
#SerializedName("fertilizerFirst")
val fertilizerFirst: String,
#SerializedName("fertilizerSecond")
val fertilizerSecond: String,
#SerializedName("fertilizerThird")
val fertilizerThird: String
)
CropActivity.kt
class CropActivity : AppCompatActivity(), CropOnItemClickListener {
private lateinit var viewModel: CropActivityViewModel
private val cropAdapter by lazy { CropAdapter(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_crop)
val repository = Repository()
val viewModelFactory = CropActivityViewModelFactory(repository)
viewModel = ViewModelProvider(this, viewModelFactory).get(CropActivityViewModel::class.java)
viewModel.getCropData()
viewModel.cropResponse.observe(this, Observer { response ->
cropAdapter.setData(response)
Log.d("dCrop", response.toString())
})
setUpCrops()
}
private fun setUpCrops() {
crop_recyclerview.layoutManager = LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL, false
)
crop_recyclerview.setHasFixedSize(true)
crop_recyclerview.adapter = cropAdapter
}
override fun onClick(item: CropData, position: Int) {
val intent = Intent(this, CropDetailsActivity::class.java)
intent.putExtra("name", item.cropName)
intent.putExtra("image", item.cropImage)
intent.putExtra("intro", item.cropDetails)
intent.putExtra("process", item.cropProcess)
intent.putExtra("type", item.cropType)
intent.putExtra("time", item.cropTime)
startActivity(intent)
}
}
CropAdapter.kt
class CropAdapter(private val cropOnItemClickListener: CropOnItemClickListener) :
RecyclerView.Adapter<CropAdapter.ViewHolder>() {
private var cropList = emptyList<CropData>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.crop_row,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.crop_name.text = cropList[position].cropName
holder.itemView.crop_details.text = cropList[position].cropDetails
holder.itemView.crop_time.text = cropList[position].cropTime
holder.itemView.setOnClickListener{
cropOnItemClickListener.onClick(cropList[position],position)
}
}
override fun getItemCount(): Int {
return cropList.size
}
fun setData(newList: List<CropData>){
notifyDataSetChanged()
cropList = newList
notifyDataSetChanged()
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView)
}
CropDetailsActivity.kt
class CropDetailsActivity : AppCompatActivity() {
private lateinit var viewModel: CropDetailsActivityViewModel
private val fertlizerAdapter by lazy { FertilizerAdapter() }
private val cropFertilizerAdapter by lazy { FertilizerAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_crop_details)
val bundle:Bundle? = intent.extras
crop_details_name.text = bundle!!.getString("name")
val i: String = bundle!!.getString("intro")
crop_details_intro.text = i
Glide.with(this).load(bundle.getString("image")).into(crop_details_image);
val j: String = bundle!!.getString("process")
crop_details_process.text = j
crop_details_time.text = bundle!!.getString("time")
crop_details_type.text = bundle!!.getString("type")
val repository = Repository()
val viewModelFactory = CropDetailsActivityViewModelFactory(repository)
viewModel = ViewModelProvider(this, viewModelFactory).get(CropDetailsActivityViewModel::class.java)
viewModel.getFertilizer()
viewModel.fResponse.observe(this, Observer {
cropFertilizerAdapter.setData(it)
})
crop_details_recyclerview.layoutManager = LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL, false
)
crop_details_recyclerview.setHasFixedSize(true)
crop_details_recyclerview.adapter = cropFertilizerAdapter
}
}
Better understanding see the image
[1]: https://i.stack.imgur.com/BtPqe.jpg
I want to show CropFertilizer list in CropDetailsActivity.How can i do this?

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

Categories

Resources