2

I have method called getEventId in the DataAdapter class but I'm unable to access it from my MainActivity class and not sure why?

DataAdapter

class DataAdapter (events: ArrayList<Array<String>>) : RecyclerView.Adapter<DataAdapter.ViewHolder>() {

  private val TAG = "Adapter"

  private val events = events

  inner class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
      var id = ""
      val title: TextView = view.txtTitle
      val date: TextView = view.txtDate
  }

  fun getEventId (position: Int): Int? {
    return if (events.isNotEmpty()) events[position][0].toInt() else null
  }

  .....
}

MainActivity

class MainActivity : AppCompatActivity(), RecyclerItemClickListener.OnRecyclerClickListener {

  private val eventsDatabase: DatabaseHelper = DatabaseHelper(this)
  private var events = ArrayList<Array<String>>()

  ...

  override fun onItemClick(view: View, position: Int) {
      var itemId = DataAdapter.getEventId(position)

      Toast.makeText(this, "Normal tap on id: $itemId", Toast.LENGTH_SHORT).show()
  }

  ...
}

1 Answer 1

5

You need to call getEventId(position) on an instance of the class not on the class itself.

class MainActivity : AppCompatActivity(), RecyclerItemClickListener.OnRecyclerClickListener {

  private val eventsDatabase: DatabaseHelper = DatabaseHelper(this)
  private var events = ArrayList<Array<String>>()
  private var adapter = DataAdapter(arrayListOf<Array<String>>())

  ...

  override fun onItemClick(view: View, position: Int) {
      var itemId = adapter.getEventId(position)

      Toast.makeText(this, "Normal tap on id: $itemId", Toast.LENGTH_SHORT).show()
  }

  ...
}

If you need to call getEventId(position) without instantiating your class (which I doubt might be the case here), you need to add it in your companion object.

class DataAdapter (events: ArrayList<Array<String>>) : RecyclerView.Adapter<DataAdapter.ViewHolder>() {

  private val TAG = "Adapter"

  private val events = events

  inner class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
      var id = ""
      val title: TextView = view.txtTitle
      val date: TextView = view.txtDate
  }



  companion object{
     fun getEventId (position: Int): Int? {
         return if (events.isNotEmpty()) events[position][0].toInt() else null
     } 
  }
  .....
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works: val dataAdapter = DataAdapter(events) var itemId = dataAdapter.getEventId(position)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.