Problem with RecyclerView OnClick (kotlin) - android-studio

sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?
My Adapter:
package com.example.practica1.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video
class MainAdapter(private val context: Context, private val videos: List<Video>): RecyclerView.Adapter<MainAdapter.ViewHolder>(){
private lateinit var mListener: onItemClickListener
interface onItemClickListener{
fun onItemClick(position: Int)
}
fun setOnClickListener(listener: onItemClickListener){
mListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
return ViewHolder(view, mListener)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val video = videos[position]
holder.title.text = video.data.short_title
holder.serieTitle.text = video.data.show.title
holder.durationTitle.text = video.data.video.duration + " seg"
Glide.with(context)
.load(video.data.imagepath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.override(400, 400)
.centerCrop()
.into(holder.imagePrev)
}
override fun getItemCount() = videos.size
inner class ViewHolder(itemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
val title: TextView = itemView.findViewById(R.id.videoTitle)
val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)
init{
itemView.setOnClickListener{
listener.onItemClick(adapterPosition)
}
}
}
}
The fragment in which I tried to implement the method:
package com.example.practica1.fragments
import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MenuFragment : Fragment() {
private var _binding: FragmentMenuBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMenuBinding.inflate(inflater, container, false)
val view = inflater.inflate(R.layout.fragment_menu, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val retrofit = Retrofit.Builder()
.baseUrl("https://www.cartoonnetwork.com.co")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiInterface::class.java)
showProgress()
api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
if (response.isSuccessful()) {
d("daniel", "onResponse ${response.body()!![0].id}")
if (response.body()!!.size > 0) {
showData(response.body()!!)
getResult(true, "Sucess")
} else
getResult(false, response.message())
hideProgress()
}
}
override fun onFailure(call: Call<List<Video>>, t: Throwable) {
d("daniel", "onFailure")
getResult(false, "Request Timeout. Please Try Again!")
hideProgress()
}
})
binding.search.setOnClickListener { v -> showDialog(v) }
}
fun showData(videos: List<Video>){
val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
var adap = MainAdapter(requireContext(), videos)
test.apply{
adapter = adap
}
adap.setOnClickListener(object: MainAdapter.onItemClickListener{
override fun onItemClick(position: Int){
d("test", "test")
}
})
}
fun showProgress(){
binding.swipeRefresh.setRefreshing(true)
binding.emptyView.setVisibility(View.GONE)
binding.shimmer.startShimmer()
binding.shimmer.setVisibility(View.VISIBLE)
binding.recyclerViewMenu.setVisibility(View.GONE)
}
fun hideProgress(){
binding.swipeRefresh.setRefreshing(false)
binding.shimmer.stopShimmer()
binding.shimmer.setVisibility(View.GONE)
binding.recyclerViewMenu.setVisibility(View.VISIBLE)
}
fun getResult(status: Boolean, message: String){
if(!status) {
binding.emptyView.setVisibility(View.VISIBLE)
binding.textEmptyErr.setText(message)
}
else
binding.emptyView.setVisibility((View.GONE))
}
private fun showDialog(view: View){
BottomFluxDialog.inputDialog(requireActivity())
.setTextTitle("Input Title")
.setTextMessage("This is an input message")
.setRightButtonText("SUBMIT")
.setInputListener(object : OnInputListener {
override fun onSubmitInput(text: String?) {
val bundle = Bundle()
bundle.putString("search", text)
Navigation.findNavController(view)
.navigate(R.id.action_menuFragment_to_listFragment, bundle)
}
override fun onCancelInput() {}
})
.show()
}
}
Thanks!

There is no such common thin like OnItemClickListener for RecyclerView, so you have to design your own. It shouldn't be hard to implement by hand, though. What you can do, is that you can Just set OnClickListener to the whole item view and delegate it clicks to upper lambda.
class YourAdapter(
private val listener: (Video) -> Unit,
private val videos: List<Video>,
): ... {
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.itemView.setOnClickListener { v ->
if (position != RecyclerView.NO_POSITION) {
listener(videos[position])
}
}
}
}
There are no noticeable side-effects of swapping View.OnClickListener in onBindViewHolder() method.
Also, few suggestions:
Read about ListAdapterhere. Looks like it perfect fit for your usecase.
Use getAbsoluteAdapterPosition() instead of adapterPosition() method within ViewHolder, as adapters are designed to be combined. Read more about ConcatAdapter here.
You don't need to pass Context to adapter constructor. View already has context, so you can query context by calling viewHolder.itemView.context.
Make sure to use your binding. It looks like you creating your binding in MenuFragment, but later you are getting RecyclerView by id in an old-fashioned way.
Don't create adapters, that require data for creation. Instead, pass and update data as you requested from the backend. RecyclerView.Adapter is designed to be reused.

Related

Kotlin E/RecyclerView: No adapter attached; skipping layout (Adapter doesnt work)

I am using RecyclerView in my app. But I'm getting this error in the Logcat. Here is my Codes;
My Fragment
package com.ahmetkaan.kediy.Fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.ahmetkaan.kediy.R
import com.ahmetkaan.kediy.adapter.NotesAdapter
import com.ahmetkaan.kediy.database.NotesDatabase
import com.ahmetkaan.kediy.databinding.FragmentHomeBinding
import com.ahmetkaan.kediy.entities.Notlar
import kotlinx.coroutines.launch
import java.util.*
import kotlin.collections.ArrayList
class Home : BaseFragment() {
lateinit var binding : FragmentHomeBinding
var arrNotes = ArrayList<Notlar>()
var notesAdapter: NotesAdapter = NotesAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
launch {
context?.let {
val notes = NotesDatabase.getDatabase(it).noteDao().getAllNotes()
notesAdapter.setData(notes)
arrNotes = notes as ArrayList<Notlar>
binding.recyclerView.adapter = notesAdapter
}
}
binding.searchView.setOnQueryTextListener( object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(p0: String?): Boolean {
return true
}
override fun onQueryTextChange(p0: String?): Boolean {
var tempArr = ArrayList<Notlar>()
for (arr in arrNotes){
if (arr.not!!.toLowerCase(Locale.getDefault()).contains(p0.toString())){
tempArr.add(arr)
}
}
notesAdapter.setData(tempArr)
notesAdapter.notifyDataSetChanged()
return true
}
})
notesAdapter.setOnClickListener(onClicked)
binding.notEkle.setOnClickListener {
val action = HomeDirections.actionHome2ToNotOlustur()
Navigation.findNavController(requireActivity(), R.id.fragmentContainerView).navigate(action)
}
binding.calendar.setOnClickListener {
val action = HomeDirections.actionHome2ToCalendar2()
Navigation.findNavController(requireActivity(), R.id.fragmentContainerView).navigate(action)
}
}
private val onClicked = object :NotesAdapter.OnItemClickListener {
override fun onClicked(notesId: Int) {
val fragment: Fragment
val bundle = Bundle()
bundle.putInt("noteId", notesId)
fragment = NotOlustur.newInstance()
fragment.arguments = bundle
val action = HomeDirections.actionHome2ToNotOlustur()
Navigation.findNavController(requireActivity(), R.id.fragmentContainerView)
.navigate(action)
}
}
}
My Adapter
package com.ahmetkaan.kediy.adapter
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.graphics.drawable.toDrawable
import androidx.recyclerview.widget.RecyclerView
import com.ahmetkaan.kediy.R
import com.ahmetkaan.kediy.entities.Notlar
import kotlin.collections.ArrayList
class NotesAdapter() :
RecyclerView.Adapter<NotesAdapter.NotesViewHolder>() {
var listener:OnItemClickListener? = null
var arrList = ArrayList<Notlar>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesViewHolder {
return NotesViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_notlar,parent,false)
)
}
override fun getItemCount(): Int {
return arrList.size
}
fun setData(arrNotesList: List<Notlar>){
arrList = arrNotesList as ArrayList<Notlar>
}
fun setOnClickListener(listener1: OnItemClickListener){
listener = listener1
}
override fun onBindViewHolder(holder: NotesViewHolder, position: Int) {
holder.itemView.findViewById<TextView>(R.id.theNotC).text = arrList[position].not
holder.itemView.findViewById<TextView>(R.id.dateTimeC).text = arrList[position].dateTime
if (arrList[position].impPathBackground != null){
holder.itemView.findViewById<ImageView>(R.id.backgroundC).setImageBitmap(BitmapFactory.decodeFile(arrList[position].impPathBackground))
} else {
holder.itemView.findViewById<ImageView>(R.id.backgroundC).setImageDrawable(R.drawable.ronin.toDrawable())
}
if (arrList[position].impPathBackground != null){
holder.itemView.findViewById<ImageView>(R.id.backgroundC).setImageBitmap(BitmapFactory.decodeFile(arrList[position].impPathLogo))
} else {
holder.itemView.findViewById<ImageView>(R.id.backgroundC).setImageDrawable(R.drawable.logo1.toDrawable())
}
holder.itemView.findViewById<CardView>(R.id.cardView).setOnClickListener {
listener!!.onClicked(arrList[position].id!!)
}
}
class NotesViewHolder(view:View) : RecyclerView.ViewHolder(view){
}
interface OnItemClickListener{
fun onClicked(noteId:Int)
}
}
I searched a lot on the internet but I didn't understand much because they are all in java language. It didn't work even though I tried what I understood. Unlike others, I used CoroutineScope(launch) I think it was because of it, but I'm not sure. What should i do?
Setting the adapter should be in the main thread. But you wrapped it in launch.
binding.recyclerView.adapter = notesAdapter

RecyclerView ItemOnClickListener doesn't work

sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?
My Adapter:
package com.example.practica1.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video
class MainAdapter(private val context: Context, private val videos: List<Video>,
val listener: MyOnClickListener
): RecyclerView.Adapter<MainAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val video = videos[position]
holder.title.text = video.data.short_title
holder.serieTitle.text = video.data.show.title
holder.durationTitle.text = video.data.video.duration + " seg"
Glide.with(context)
.load(video.data.imagepath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.override(400, 400)
.centerCrop()
.into(holder.imagePrev)
}
override fun getItemCount() = videos.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val title: TextView = itemView.findViewById(R.id.videoTitle)
val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)
init{
itemView.setOnClickListener{
val position = adapterPosition
listener.onClick(position)
}
}
}
interface MyOnClickListener{
fun onClick(position: Int)
}
}
The fragment in which I tried to implement the method (The toast message doesn't appear)
package com.example.practica1.fragments
import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MenuFragment : Fragment() {
private var _binding: FragmentMenuBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMenuBinding.inflate(inflater, container, false)
val view = inflater.inflate(R.layout.fragment_menu, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val retrofit = Retrofit.Builder()
.baseUrl("https://www.cartoonnetwork.com.co")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiInterface::class.java)
showProgress()
api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
if (response.isSuccessful()) {
d("daniel", "onResponse ${response.body()!![0].id}")
if (response.body()!!.size > 0) {
showData(response.body()!!)
getResult(true, "Sucess")
} else
getResult(false, response.message())
hideProgress()
}
}
override fun onFailure(call: Call<List<Video>>, t: Throwable) {
d("daniel", "onFailure")
getResult(false, "Request Timeout. Please Try Again!")
hideProgress()
}
})
binding.search.setOnClickListener { v -> showDialog(v) }
}
fun showData(videos: List<Video>){
val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
test.apply{
adapter = MainAdapter(context, videos, object: MainAdapter.MyOnClickListener{
override fun onClick(position: Int) {
Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
}
})
}
}
fun showProgress(){
binding.swipeRefresh.setRefreshing(true)
binding.emptyView.setVisibility(View.GONE)
binding.shimmer.startShimmer()
binding.shimmer.setVisibility(View.VISIBLE)
binding.recyclerViewMenu.setVisibility(View.GONE)
}
fun hideProgress(){
binding.swipeRefresh.setRefreshing(false)
binding.shimmer.stopShimmer()
binding.shimmer.setVisibility(View.GONE)
binding.recyclerViewMenu.setVisibility(View.VISIBLE)
}
fun getResult(status: Boolean, message: String){
if(!status) {
binding.emptyView.setVisibility(View.VISIBLE)
binding.textEmptyErr.setText(message)
}
else
binding.emptyView.setVisibility((View.GONE))
}
private fun showDialog(view: View){
BottomFluxDialog.inputDialog(requireActivity())
.setTextTitle("Input Title")
.setTextMessage("This is an input message")
.setRightButtonText("SUBMIT")
.setInputListener(object : OnInputListener {
override fun onSubmitInput(text: String?) {
val bundle = Bundle()
bundle.putString("search", text)
Navigation.findNavController(view)
.navigate(R.id.action_menuFragment_to_listFragment, bundle)
}
override fun onCancelInput() {}
})
.show()
}
}
Thanks!
If your data is showing in the recycler view and you are getting crash on item click than
replace this toast link :-
Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
with this :-
Toast.makeText(requireContext(), "$position", Toast.LENGTH_SHORT).show()
or if your video list is not visible in recycler view than you need to implement layout manager in recycler view you can add it on xml or in code also.

How can I share a variable from MainActivity to a fragment?

I want to share variable : master between MainActivity to ListAdapter. Can you tell me how to do it ? I tried with bundles and a lot of things, but in the end I received errors.
Main Activity
package com.example.roomapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.roomapp.AESKnowledgeFcatory.decrypt
import com.example.roomapp.HashUtils.sha256
import com.example.roomapp.fragments.add.AddFragment
import kotlinx.android.synthetic.main.activitycreate.*
import kotlinx.android.synthetic.main.activitylogin.*
import kotlinx.android.synthetic.main.custom_row.*
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
class MainActivity : AppCompatActivity() {
var master: String = "0"
var checkLogin2: String = ""
var lf_ch = false
fun createMaster(v:View){
this.master = this.editmasterpass.text.toString()
val sharedPref = this.getPreferences(MODE_PRIVATE) ?:return
with (sharedPref.edit()){
putString("cheie",sha256(master))
commit()
}
val sharedPref2 = this.getPreferences(MODE_PRIVATE) ?: return
val defaultValue = sharedPref2.getString("cheie", "ABA")
System.out.println(" Key value = " + defaultValue)
setContentView(R.layout.activity_main)
}
fun checklogin(v: View)
{
this.checkLogin2 = this.editTextTextPassword.text.toString()
val castoras = this.getPreferences(MODE_PRIVATE)
val defaultValue2 = castoras.getString("cheie", "ABA")
if(sha256(this.checkLogin2)==defaultValue2.toString())
{
setContentView(R.layout.activity_main)
}
else {
textView3.text="Incorrect Password"
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val castoras = this.getPreferences(MODE_PRIVATE)
val defaultValue2 = castoras.getString("cheie", "key not found")
System.out.println("Abracanabra= "+defaultValue2.toString())
if ((defaultValue2.toString())=="key not found") {
setContentView(R.layout.activitycreate)
}
else {
setContentView((R.layout.activitylogin))
}
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.fragment)
return navController.navigateUp() || super.onSupportNavigateUp()
}
// cum sa pasam variabila master
}
ListAdapter
package com.example.roomapp.fragments.list
import android.app.PendingIntent.getActivity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.roomapp.AESKnowledgeFcatory.encrypt
import com.example.roomapp.R
import com.example.roomapp.data.User
import kotlinx.android.synthetic.main.custom_row.view.*
import android.content.SharedPreferences
import com.example.roomapp.MainActivity
class ListAdapter: RecyclerView.Adapter<ListAdapter.MyViewHolder>() {
private var userList = emptyList<User>()
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.custom_row, parent, false))
}
override fun getItemCount(): Int {
return userList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = userList[position]
holder.itemView.id_txt.text = currentItem.id.toString()
holder.itemView.firstName_txt.text = currentItem.firstName
// I want to use the master string here, master+currentItem.salt
holder.itemView.lastName_txt.text = encrypt(currentItem.lastName,currentItem.salt)
holder.itemView.salt_txt.text = currentItem.salt
}
fun setData(user: List<User>){
this.userList = user
notifyDataSetChanged()
}
}
I need a method that can pass me the "master" variable to ListAdapter, because I need to pass certain informations.
List fragment
package com.example.roomapp.fragments.list
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.roomapp.R
import com.example.roomapp.data.UserViewModel
import kotlinx.android.synthetic.main.fragment_list.view.*
class ListFragment() : Fragment() {
private lateinit var mUserViewModel: UserViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_list, container, false)
// Recyclerview
val adapter = ListAdapter()
val recyclerView = view.recyclerview
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
// UserViewModel
mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
mUserViewModel.readAllData.observe(viewLifecycleOwner, Observer { user ->
adapter.setData(user)
})
view.floatingActionButton.setOnClickListener {
findNavController().navigate(R.id.action_listFragment_to_addFragment)
}
return view
}
}
You can simply add a constructor parameter in your ListAdapter and pass the value of master string when creating the ListAdapter in MainActivity, this can be done as
class ListAdapter(private val master: String):
RecyclerView.Adapter<ListAdapter.MyViewHolder>()
and in your MainActivity, where you create object of ListAdapter, pass the value of master
listAdapter = ListAdapter(master)
Now you can use master in your ListAdapter as you like

getting adapter type mismatch in Android Studio

basically i am trying to create a recycler view and this the main activity
i am getting error at
recyclerView.adapter = adapter
package com.example.newsorning
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager = LinearLayoutManager(this)
val items = fetchData()
val adapter = NewsListAdapter(items)
recyclerView.adapter = adapter
}
private fun fetchData():ArrayList<String>{
val list = ArrayList<String>()
for (i in 0 until 100){
list.add("item $i")
}
return list
}
}
this is where i created adpater
//newsListadapter
package com.example.newsorning
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class NewsListAdapter(private val item:ArrayList<String>):
RecyclerView.Adapter<NewsViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): NewsViewHolder {
val view = LayoutInflater.from(p0.context).inflate(R.layout.item_news,p0,false)
return NewsViewHolder(view)
}
override fun getItemCount(): Int {
return item.size
}
override fun onBindViewHolder(p0: NewsViewHolder, p1: Int) {
val currentItem = item[p1]
p0.titleView.text = currentItem
}
}
class NewsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleView : TextView = itemView.findViewById(R.id.titleView)
}
This may be due to you using the old, deprecated support library RecyclerView (android.support.v7) instead of the Jetpack RecyclerView (androidx). Maybe one of the libraries you're using still uses the old support library, so it was in your namespace and you accidentally selected it when choosing which class to import. You need to change the line
import android.support.v7.widget.RecyclerView
to
import androidx.recyclerview.widget.RecyclerView
in both of these files. And you need to enable Jetifier according to these directions.

Studio shows an error when I try to startActivity() from Recycler View Adapter

Building my first app and hitting an error I can't figure out. I have a recycler view that shows a list of cards. I want to click the card and open another activity.
Here is my code:
import android.content.Context
import android.content.Intent
import android.support.v4.content.ContextCompat.startActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.list_tank_item.view.*
class TankAdapter(val context: Context, val tanks: List<Tank>) : RecyclerView.Adapter<TankAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, p1: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.list_tank_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return tanks.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val tank = tanks[position]
holder.setData(tank, position)
}
inner class ViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview) {
var currentTank: Tank? = null
var currentPosition: Int = 0
init {
itemView.setOnClickListener{
val intent = Intent(context, TankOverviewActivity::class.java)
var tank_id = currentTank._id.toString()
intent.putExtra("tank_id", tank_id)
startActivity(intent)
}
itemView.imgEdit.setOnClickListener{
Toast.makeText(context, currentTank!!.tank_name + " Edit button clicked!", Toast.LENGTH_LONG).show()
}
}
fun setData(tank: Tank?, position: Int) {
itemView.txvTankName.text = tank!!.tank_name
itemView.txvTankCapacity.text = tank!!.tank_capacity
itemView.txvTankType.text = tank!!.tank_type
this.currentTank = tank
this.currentPosition = position
}
}
}
And here a screen of of android studio:
Android Studio problem
What am I doing wrong?
Try as follow
import ...
//use your context as member of your class put private as modifier
class TankAdapter(private val context: Context, val tanks: List<Tank>) : RecyclerView.Adapter<TankAdapter.ViewHolder>() {
...
inner class ViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview) {
...
init {
itemView.setOnClickListener {
...
//call startActivity from context
context.startActivity(intent)
}
...
}
...
}
}

Resources