I have a RecyclerView created in Kotlin and would like to save the data from the RecyclerView (the ArrayList) for example with GSON Libary. I've already searched a lot but can't find a working solution. Here's my current code: (without saving function)
MainActivity.kt:
class MainActivity : AppCompatActivity(), ExampleAdapter.OnItemClickListener {
private val exampleList = generateDummyList(500)
private val adapter = ExampleAdapter(exampleList, this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recycler_view.adapter = adapter
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.setHasFixedSize(true)
}
fun insertItem(view: View) {
val index = Random.nextInt(8)
val newItem = ExampleItem(
R.drawable.ic_android,
"New item at position $index",
"Line 2"
)
exampleList.add(index, newItem)
adapter.notifyItemInserted(index)
}
fun removeItem(view: View) {
val index = Random.nextInt(8)
exampleList.removeAt(index)
adapter.notifyItemRemoved(index)
}
override fun onItemClick(position: Int) {
Toast.makeText(this, "Item $position clicked", Toast.LENGTH_SHORT).show()
val clickedItem = exampleList[position]
clickedItem.text1 = "Clicked"
adapter.notifyItemChanged(position)
}
private fun generateDummyList(size: Int): ArrayList<ExampleItem> {
val list = ArrayList<ExampleItem>()
for (i in 0 until size) {
val drawable = when (i % 3) {
0 -> R.drawable.ic_android
1 -> R.drawable.ic_audio
else -> R.drawable.ic_sun
}
val item = ExampleItem(drawable, "Item $i", "Line 2")
list += item
}
return list
}
}
ExampleItem.kt:
data class ExampleItem(val imageResource: Int, var text1: String, var text2: String)
ExampleAdapter.kt:
class ExampleAdapter(
private val exampleList: List<ExampleItem>,
private val listener: OnItemClickListener) :
RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.example_item,
parent, false)
return ExampleViewHolder(itemView)
}
override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
val currentItem = exampleList[position]
holder.imageView.setImageResource(currentItem.imageResource)
holder.textView1.text = currentItem.text1
holder.textView2.text = currentItem.text2
}
override fun getItemCount() = exampleList.size
inner class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
val imageView: ImageView = itemView.image_view
val textView1: TextView = itemView.text_view_1
val textView2: TextView = itemView.text_view_2
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
interface OnItemClickListener {
fun onItemClick(position: Int)
}
}
First you need to convert you Data in to json by using json object in onBindViewHolder using
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
And if you want to save then you can use shared preferences.
Related
I want to show my JSON data in the sticky header recyclerview date-wise from the assets folder.The list of Array is receive but not shown in recyclerview. I don't know where is my mistake. when I add toast it shows a complete JSON List.but not shown in recyclerview.
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
var jobsArray = arrayListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadJSONFromAsset()
}
private fun loadJSONFromAsset() {
try {
val json: String?
val inputStream: InputStream = assets.open("test.json")
json = inputStream.bufferedReader().use { it.readText() }
var jsonArray = JSONArray(json)
for (i in 0..jsonArray.length()) {
var jsonObject = jsonArray.getJSONObject(i)
jobsArray.add(jsonObject.getString("data"))
}
viewManager = LinearLayoutManager(this)
recyclerView = findViewById<RecyclerView>(R.id.recycler_view).apply {
viewAdapter = JobsAdapter(jobsArray)
layoutManager = viewManager
adapter = viewAdapter
}
recyclerView.addItemDecoration(
StickyHeaderItemDecoration(
recyclerView,
viewAdapter as JobsAdapter
)
)
} catch (ex: IOException) {
ex.printStackTrace()
}
}
}
Adapter Class
class JobsAdapter(
private var jobsArray: ArrayList<String>): RecyclerView.Adapter<RecyclerView.ViewHolder>(), StickyHeaderItemDecoration.StickyHeaderInterface {
override fun isHeader(itemPosition: Int): Boolean {
return true
//return startTime[itemPosition].
}
override fun bindHeaderData(header: View, headerPosition: Int) {
((header as ConstraintLayout).getChildAt(0) as TextView).text =
jobsArray[headerPosition]
}
override fun getHeaderLayout(headerPosition: Int): Int {
return R.layout.row_header
}
override fun getHeaderPositionForItem(itemPosition: Int): Int {
var headerPosition = 0
var position = itemPosition
do {
if (this.isHeader(position)) {
headerPosition = position
break
}
position -= 1
} while (position >= 0)
return headerPosition
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if(viewType == TYPE_HEADER) {
ViewHolderHeader(LayoutInflater.from(parent.context)
.inflate(R.layout.row_header, parent, false))
} else {
ViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.user_item, parent, false))
}
}
override fun getItemCount() = jobsArray.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if(holder is ViewHolder) {
holder.nameView.text = jobsArray[position]
} else if(holder is ViewHolderHeader) {
holder.headerView.text = jobsArray[position]
}
}
override fun getItemViewType(position: Int): Int {
return if(true) {
TYPE_HEADER
} else {
TYPE_ITEM
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val nameView = view.findViewById<TextView>(R.id.tv_name)
}
class ViewHolderHeader(view: View) : RecyclerView.ViewHolder(view) {
val headerView = view.findViewById<TextView>(R.id.headerView)
}
}
Json Data(Im puting small chunk of json)
{
"data": [
{
"id": 2158,
"title": "job schedule 13",
"description": "job schedule 13 description\n",
"currency": "$",
"type": "2",
"days": "2",
"start_time": "2021-09-13 13:20:57",
"end_time": "2021-09-29 13:50:00",
"total_workers": 30,
"hourly_rate": 12,
"status": "Pending",
"user": {
"id": 165,
"name": "Asad Employer",
"email": "",
"mobile_number": "+92331435343",
"status": "Active",
"street_address": "ichra"
},
]
Create data class for the json data
data class AssetJSON(
val data: List<Data>
)
data class Data (
val id: Long,
val title: String,
val description: String,
val currency: String,
val type: String,
val days: String,
val start_time: String,
val end_time: String,
val total_workers: Long,
val hourly_rate: Long,
val status: String,
val user: User
)
data class User (
val id: Long,
val name: String,
val email: String,
val mobile_number: String,
val status: String,
val street_address: String
)
Install Gson into your project
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Parse Json file into Json String as same as you does
private fun loadJSONFromAsset(context: Context, fileName: String): String {
return try {
context.assets.open(fileName).bufferedReader().use { it.readText() }
} catch (e: IOException) {
e.printStackTrace()
null
}
}
Parse Json String into data class
val jsonString = loadJSONFromAsset(this, "test.json")
val data = Gson().fromJson(jsonString, AssetJSON::class.java)
// "data" now is your class
Pass this data into your adapter and see what error is thrown?
I have recyclerView which is having multiple items. Every item is holding a checkbox to select that item. I want to get the selected item in another ArrayList and pass it to my MainActivity. On accept click I called getselecteditem() but getselecteditem() function always returns null. Here is my adapter code.
class orderAdapter(val items: List<Orders>, val context: Context) :
RecyclerView.Adapter<ViewHolder>() {
var selectedItems: ArrayList<String> = ArrayList()
var selectedList: ArrayList<String> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(context).inflate(
R.layout.order_queue_item,
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvQuantity?.text = "Quantity: ${items.get(position).totalCount}"
holder.tvOrderId?.text = "Order No. : ${items.get(position).orderNumber}"
holder.tvSum?.text = "Sum: ${items.get(position).totalPrice}"
/* holder.cbSelectOrder?.setOnClickListener(object : View.OnClickListener{
override fun onClick(v: View?) {
selectedItems.add(items.get(position))
Log.e("selected"," "+selectedItems.size)
}
})*/
holder.cbSelectOrder.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
selectedList.add(items.get(position).id)
Log.e("selected", "items " + items.get(position).id)
Log.e("selected", "selected " + selectedList.size)
Log.e("selected", "selected " + selectedList.toString())
//var size = selectedItems.size
// selectedList.addAll(selectedItems)
notifyDataSetChanged()
} else if(!isChecked) {
selectedList.remove(items.get(position).id)
Log.e("selected", "items " + items.get(position).id)
Log.e("selected", "selected " + selectedList.size)
Log.e("selected", "selected " + selectedList.toString())
notifyDataSetChanged()
}
notifyDataSetChanged()
}
holder.btnView?.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
val intent = Intent(context, ReviewOrderActivity::class.java)
intent.putExtra("orderId", items.get(position).id.toString())
context.startActivity(intent) // put context infront
}
})
}
fun getSelected(): ArrayList<String> {
Log.e("selected", "selectedlist " + selectedList.size)
Log.e("selected", "selectedlist " + selectedList.toString())
return selectedList
}
override fun getItemCount(): Int {
return items.size
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
// Holds the TextView that will add each animal to
val tvQuantity = view.findViewById<TextView>(R.id.tv_quantity)
val tvOrderId = view.findViewById<TextView>(R.id.tv_order_id)
val tvSum = view.findViewById<TextView>(R.id.tv_sum)
val btnView = view.findViewById<Button>(R.id.btn_view)
val cbSelectOrder = view.findViewById<CheckBox>(R.id.cb_button)
}
You need a callback which lets to fetch selected order and update list on every selected or un-select order
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
....
public interface Listener {
fun getSelectedOrderList(list : ArrayList<String>);
}
}
orderAdapter constructor will have listener instance which will update selected list in main activity.
class orderAdapter(val items: List<Orders>, val context: Context, private val listener: ViewHolder.Listener)
In MainActivity recyclerview listener will get list.
recyclerView.adapter = orderAdapter(getOrderList(), this, object : ViewHolder.Listener {
override fun getSelectedOrderList(list: ArrayList<String>) {
Log.d(TAG, "Selected order List : $list")
}
})
orderAdapter class
class orderAdapter(val items: List<Orders>, val context: Context, private val listener: ViewHolder.Listener) :
RecyclerView.Adapter<ViewHolder>() {
var selectedItems: ArrayList<String> = ArrayList()
var selectedList: ArrayList<String> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(context).inflate(R.layout.order_queue_item, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvQuantity.text = "Quantity: ${items.get(position).totalCount}"
holder.tvOrderId?.text = "Order No. : ${items.get(position).orderNumber}"
holder.tvSum?.text = "Sum: ${items.get(position).totalPrice}"
holder.cbSelectOrder.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
selectedList.add(items.get(position).id)
notifyDataSetChanged()
} else if (!isChecked) {
selectedList.remove(items.get(position).id)
notifyDataSetChanged()
}
listener.getSelectedOrderList(selectedList)
notifyDataSetChanged()
}
holder.btnView.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
Toast.makeText(context, "View Button Clicked", Toast.LENGTH_SHORT).show()
}
})
}
fun getSelected(): ArrayList<String> {
return selectedList
}
override fun getItemCount(): Int {
return items.size
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
// Holds the TextView that will add each animal to
val tvQuantity = view.findViewById<TextView>(R.id.tv_quantity)
val tvOrderId = view.findViewById<TextView>(R.id.tv_order_id)
val tvSum = view.findViewById<TextView>(R.id.tv_sum)
val btnView = view.findViewById<Button>(R.id.btn_view)
val cbSelectOrder = view.findViewById<CheckBox>(R.id.cb_button)
public interface Listener {
fun getSelectedOrderList(list : ArrayList<String>);
}
}
There is a delete button on my recylerview item when I click it I m showing a alert dialog when I click yes button I want to refresh my recylerview but I could'not. I call directly notifyDataSetChanged in adapter at the end of the my code but it does not work.
MyAlertDialog(In my adapter)
mAlertDialog.setPositiveButton("Yes") { dialog, id ->
val databaseHandler: DBHelper = DBHelper(holder.itemView.context)
val removedMed = Medicine(id = medicine.id,name = medicine.name,amount = medicine.amount,description = medicine.description)
databaseHandler.deleteMedicine(removedMed)
dialog.dismiss()
notifyDataSetChanged()
}
Mainactivity
class MainActivity : AppCompatActivity() {
private var adapter: MedicineAdapter? = null
private var medicineList : ArrayList<Medicine> = arrayListOf()
private var recyclerView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getDataFromDb()
}
fun getDataFromDb(){
val context = this
val db = DBHelper(context)
recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView
adapter = MedicineAdapter(this, db.readData())
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = layoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
// set the adapter
recyclerView!!.adapter = adapter
adapter!!.notifyDataSetChanged()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.addBtn -> {
val intent = Intent(this,AddNewMedicine::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
getDataFromDb()
}
}
MedicineAdapter
class MedicineAdapter(
private val mainActivity: MainActivity,
val medicineList: ArrayList<Medicine>)
: RecyclerView.Adapter<MedicineAdapter.ListItemHolder>(){
override fun onCreateViewHolder(
parent: ViewGroup, viewType: Int): ListItemHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.medicine_items, parent, false)
return ListItemHolder(itemView)
}
inner class ListItemHolder(view: View) :
RecyclerView.ViewHolder(view),
View.OnClickListener {
internal var name = view.findViewById<TextView>(R.id.name)
internal var amount = view.findViewById<TextView>(R.id.amount)
internal var description = view.findViewById<TextView>(R.id.description)
internal var deleteButton = view.findViewById<ImageButton>(R.id.deleteBtn)
internal var editButton = view.findViewById<ImageButton>(R.id.editBtn)
init {
view.isClickable = true
view.setOnClickListener(this)
deleteButton.setOnClickListener(this)
editButton.setOnClickListener(this)
}
override fun onClick(view: View) {
//val intentToCarPager = Intent(view!!.context, CarPagerActivity::class.java)
//view.context.startActivity(intentToCarPager)
}
}
override fun onBindViewHolder(holder: ListItemHolder, position: Int) {
val medicine = medicineList!![position]
holder.name.text = medicine.name
holder.amount.text = medicine.amount
holder.description.text = medicine.description
holder.deleteButton.setOnClickListener {
val mAlertDialog = AlertDialog.Builder(holder.itemView.context)
mAlertDialog.setTitle("Are you sure you want to this record!") //set alertdialog title
mAlertDialog.setPositiveButton("Yes") { dialog, id ->
val databaseHandler: DBHelper = DBHelper(holder.itemView.context)
val removedMed = Medicine(id = medicine.id,name = medicine.name,amount = medicine.amount,description = medicine.description)
databaseHandler.deleteMedicine(removedMed)
notifyDataSetChanged()
dialog.dismiss()
medicineList.removeAt(position)
notifyItemRemoved(position)
}
mAlertDialog.setNegativeButton("No") { dialog, id ->
}
mAlertDialog.show()
}
holder.editButton.setOnClickListener {
val dialog = UpdateMedicine(medicine)
val manager = (holder.itemView.context as MainActivity).supportFragmentManager
dialog.show(manager,"")
}
}
override fun getItemCount(): Int {
if (medicineList != null) {
return medicineList.size
}
return -1
}
}
I solved my problem by removing the object from the array
notifyDataSetChanged()
dialog.dismiss()
medicineList.removeAt(position)
notifyItemRemoved(position)
I have been having this issue for a long time and have tried different suggestion on similar posts but all proved futile.
Currently, I have a recyclerview that implements double click for likes. Whenever I do that the recyclerview jumps to the top of the page.
Kindly advise on what to do to stop this.
Code
private fun setDataIntoAdapter(list: List<MovieEntity?>?) {
movieAdapter = MovieAdapter(list, object : MovieAdapter.OnMovieListener {
override fun onMovieDoubleClick(movieEntity: MovieEntity, view: View) {
val fav = view.findViewById<ImageView>(R.id.redFav)
// var favMovie = convertToFavourityEntity(movieEntity)
movieEntity.favourite = true
if (fav.visibility == View.GONE) {
fav.visibility = View.VISIBLE
CoroutineScope(Main).launch {
try {
insertAndUpdate(movieEntity)
FancyToast.makeText(
context,
"${movieEntity.title} is added to favourite",
FancyToast.LENGTH_LONG,
FancyToast.SUCCESS,
true
).show()
} catch (e: Exception) {
FancyToast.makeText(
context,
"Movie has been previously added \nto favorite",
FancyToast.LENGTH_LONG,
FancyToast.ERROR,
true
).show()
}
}
} else {
fav.visibility = View.GONE
movieEntity.favourite = false
CoroutineScope(Main).launch {
try {
deleteAndUpdate(movieEntity)
FancyToast.makeText(
context,
"${movieEntity.title} is removed from favourite",
FancyToast.LENGTH_LONG,
FancyToast.INFO,
true
).show()
} catch (e: Exception) {
// Toast.makeText(context, "Movie has been previously removed \nto favorite", Toast.LENGTH_SHORT).show()
val snackbar = Snackbar
.make(
view, "Movie has been previously removed \n" +
"to favorite", Snackbar.LENGTH_LONG
)
snackbar.show()
}
}
}
}
override fun onSingleClick(movieEntity: MovieEntity, view: View) {
gotoDetails(movieEntity)
// view.deleteIcon.setOnClickListener {
// singleDeletion(movieEntity)
// }
}
})
}
private suspend fun insertAndUpdate(movieEntity: MovieEntity) {
ServiceLocator.createLocalDataSource(context!!).movieDao?.update(movieEntity)
}
Adapter
class MovieAdapter<T>(private var movies:List<T?>?, private var listener:OnMovieListener):RecyclerView.Adapter<MovieAdapter.MovieHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.movie_recycler_items, parent, false)
return MovieAdapter.MovieHolder(itemView)
}
override fun getItemCount(): Int {
return movies!!.size
}
fun setMovie(movies: List<T?>?){
this.movies = movies
notifyDataSetChanged()
}
fun getMovieAt(position: Int):T?{
return movies?.get(position)
}
override fun onBindViewHolder(holder: MovieHolder, position: Int) {
// covert.drawCornerFlag(holder)
movies?.let{
val currentMovies = it[position]
holder.bind(it[position]!!, listener)
}
}
class MovieHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
var title = itemView.findViewById<TextView>(R.id.title)
var releaseDate = itemView.findViewById<TextView>(R.id.releaseDate)
var ratingBar = itemView.findViewById<RatingBar>(R.id.ratingBar)
var imageThmbnail = itemView.findViewById<ImageView>(R.id.thumbnail)
var fav = itemView.findViewById<ImageView>(R.id.favourite)
var redFav = itemView.findViewById<ImageView>(R.id.redFav)
var rating = itemView.findViewById<TextView>(R.id.rating)
fun <T> bind(movieEntity: T, listener: OnMovieListener){
var i = 0
if(movieEntity is MovieEntity){
if(movieEntity.favourite){
redFav.visibility = View.VISIBLE
}
else{
redFav.visibility = View.GONE
}
val calendar = Calendar.getInstance()
val dateReleased = movieEntity.releaseDate?.split("-")
val year = dateReleased?.get(0)?.toInt()
val month = dateReleased?.get(1)?.toInt()
val day = dateReleased?.get(2)?.toInt()
var newDate:Date?= null
if (year != null) {
if (month != null) {
if (day != null) {
calendar.set(year, month,day)
}
}
newDate = calendar.time
}
val displayDate = newDate.toString().substring(4..7) + year.toString()
title.setText(movieEntity.title)
releaseDate.setText(displayDate)
ratingBar.numStars = 5
val ratingNum = movieEntity.rating?.toFloat()?.div(2)
rating.setText("${ratingNum!!}")
ratingBar.rating = ratingNum
Picasso.get().load(movieEntity.movieImage).into(imageThmbnail)
itemView.setOnClickListener(DoubleClick(object :DoubleClickListener{
override fun onDoubleClick(view: View?) {
Log.i("Dob", "Double clicked")
listener.onMovieDoubleClick(movieEntity, itemView)
}
override fun onSingleClick(view: View?) {
Log.i("click", "Single click")
listener.onSingleClick(movieEntity, itemView)
}
}))
}
}
}
interface OnMovieListener{
fun onMovieDoubleClick(movieEntity: MovieEntity, view:View)
fun onSingleClick(movieEntity: MovieEntity, view: View)
}
}
I need to show a list from adapter. I've got the data with calling api, but it can't showed in the interface.
this is data model Table :
data class Table(val id : String, val nama: String, val tersedia: Boolean)
this is data model Tables that contain ArrayList of Table :
data class Tables (val daftarMeja : ArrayList<Table>)
this is mu adapter :
class MejaAdapter (private val tableList: ArrayList<Table>, private val clickListener: (Table) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>(){
private lateinit var tables: Tables
override fun getItemCount(): Int {
return tableList.size
}
fun updateData(dataBaru: ArrayList<Table>) {
tableList.clear()
tableList.addAll(dataBaru)
Log.i("tableListAdapter","balbalbla" + tableList.toString())
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val cellForRow = layoutInflater.inflate(R.layout.item_meja,parent,false)
return PartViewHolder(cellForRow)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as PartViewHolder).bind(tableList[position], clickListener)
}
class PartViewHolder (itemView: View): RecyclerView.ViewHolder(itemView){
fun bind(table: Table, clicklistener: (Table) -> Unit){
itemView.tv_table_name.text = table.nama
if(table.tersedia){
itemView.container_table.setBackgroundResource(R.color.colorTableAvailable)
itemView.tv_table_name.setTextColor(Color.BLACK)
}
else {
itemView.container_table.setBackgroundResource(R.drawable.gradient)
itemView.tv_table_name.setTextColor(Color.WHITE)
}
itemView.setOnClickListener {clicklistener(table)}
}
}
}
and this fun the activity :
private lateinit var tableList: ArrayList<Tables>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_daftar_meja)
tableList = ArrayList()
/*init RecyclerView*/
recyclerView_meja.layoutManager = GridLayoutManager(this, numberOfColumns(), GridLayoutManager.VERTICAL, false)
recyclerView_meja.hasFixedSize()
/*Set Adapter*/
dataAdapter = MejaAdapter(tableItem) { tableItemClicked() }
recyclerView_meja.adapter = dataAdapter
//Show list table
val idCafe = user.cafeId
getTableList(idCafe)
}
private fun getTableList(idCafe:String){
val apiService : Service = Client.getClient()!!.create(Service::class.java)
apiService.getTable(idCafe).enqueue(object : Callback<Tables>{
override fun onResponse(call: Call<Tables>?, response: Response<Tables>?) {
Log.i("IdMeja", "id : " + response?.body())
if (response != null && response.isSuccessful) {
val listTable = response.body()
if (listTable == null) {
Toast.makeText(this#MainActivity, "Tidak ada meja", Toast.LENGTH_SHORT).show()
}
else{
tables = listTable
// update list table
Log.i("adapter", "$dataAdapter")
dataAdapter.updateData(tableList)
Toast.makeText(this#MainActivity, "hahaha$tables", Toast.LENGTH_SHORT).show()
}
}
else{
Log.i("idCafe", " $idCafe")
Toast.makeText(this#MainActivity, "Gagal dapat meja", Toast.LENGTH_SHORT).show()
}
}
override fun onFailure(call: Call<Tables>?, t: Throwable?) {
Log.i("fail",t.toString() )
Toast.makeText(this#MainActivity, "Gagal", Toast.LENGTH_SHORT).show()
}
})
}
I think the problem is in the adapter, but i don't know how to fix it.
Please help me to fix it.
We think this is a naming issue your use this line of code to name your View Holder
class MejaAdapter (private val tableList: ArrayList<Table>, private val clickListener: (Table) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>(){
Where you call it ViewHolder
Then you start using PartViewHolder
So change the code to use a consistent name PartViewHolder looks good to us
Here is our Adapter look at the naming convention used
class ViewAdapter(private val parents:List<ModelParent>):RecyclerView.Adapter<ViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.the_view,parent,false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return parents.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val parent = parents[position]
holder.textView.text = parent.dept
holder.recyclerView.apply {
layoutManager = LinearLayoutManager(holder.recyclerView.context, LinearLayout.VERTICAL, false)
adapter = ViewChildAdapter(parent.children)
}
}
inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){
val recyclerView : RecyclerView = itemView.rv_child
val textView: TextView = itemView.textView
}
}