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?
Related
I am parsing Json data in a Arraylist but data added two times i removed temp.addAll(value) line but Nothing happened.here json object is going till id 18 and i have tried adding temp.addAll(value) inside the first loop but nothing happened.please help me and answers should be in Kotlin if Possible.
here is the code
Pojo classs:
class Restaurant_info (
val id :String?=null,
val name :String?=null,
val rating : String?=null,
val cost_for_one: String?=null,
val image_url: String?=null
)
home (fragment):
lateinit var swipe: SwipeRefreshLayout
lateinit var value :ArrayList<Restaurant_info>
lateinit var temp :ArrayList<Restaurant_info>
lateinit var recyclerView :RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
var view = inflater.inflate(R.layout.fragment_dashboard, container, false)
temp= ArrayList()
value=ArrayList()
setHasOptionsMenu(true)
swipe = view.findViewById(R.id.swipe)
var relativeLayout = view.findViewById<RelativeLayout>(R.id.progresslaoout)
recyclerView = view.findViewById(R.id.recycler)
var LayoutManager = LinearLayoutManager(activity)
gettingData()
swipe.setOnRefreshListener {
gettingData()
}
relativeLayout.visibility = View.VISIBLE
val que = Volley.newRequestQueue(activity as Context)
var url = "http://13.235.250.119/v2/restaurants/fetch_result/"
var jsonObjectRequest =
object : JsonObjectRequest(Method.GET, url, null, Response.Listener {
try {
relativeLayout.visibility = View.GONE
var list =it.getJSONObject("data")
for(a in 0 until list.length()){
var data = list.getJSONArray("data")
for (i in 0 until data.length()) //compiler yhi bolta h ki tum null aray ki length le rhe ho
{
var jsonobject = data.getJSONObject(i)
var values= Restaurant_info (
jsonobject.getString("id"),
jsonobject.getString("name"),
jsonobject.getString("rating"),
jsonobject.getString("cost_for_one"),
jsonobject.getString("image_url")
)
value.add(values)
//
}
}
temp.addAll(value)
recyclerView.adapter = adapter1(activity as Context, temp)
recyclerView.layoutManager = LayoutManager
} catch (e: JSONException) {
makeText(context, "some error occured catch", Toast.LENGTH_SHORT).show()
}
}, Response.ErrorListener {
makeText(context, "some error occured sorry", Toast.LENGTH_SHORT).show()
}) {
override fun getHeaders(): MutableMap<String, String> {
val header = HashMap<String, String>()
header.put("value-type", "application/json")
header.put("token", " 9bf534118365f1")
return header
}
}
que.add(jsonObjectRequest)
return view
}
fun gettingData() {
if (connection().ConnectionChecking(activity as Context)) {
} else {
var build = AlertDialog.Builder(activity as Context)
build.setTitle("Not Connected")
build.setMessage("please check your internet Connection")
build.setPositiveButton("try again") { text, listner ->
startActivityForResult(Intent(Settings.ACTION_WIRELESS_SETTINGS), 0)
}
build.setNegativeButton("cancel") { text, listner ->
}
build.create()
build.show()
}
swipe.isRefreshing = false
}
#SuppressLint("NewApi")
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.icon,menu)
var item=menu.findItem(R.id.search)
var search=item?.actionView as SearchView
search.onActionViewExpanded()
search.focusable
search.requestFocus()
search.requestFocusFromTouch()
search.queryHint= "enter food name"
search.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(p0: String?): Boolean {
return true
}
#SuppressLint("NotifyDataSetChanged")
override fun onQueryTextChange(p0: String?): Boolean {
temp.clear()
var text= p0?.lowercase(Locale.getDefault())
if (text!!.isNotEmpty()) {
value.forEach {
//if(it.lowercase(Locale.getDefault()).contains(text))
if (it.name?.lowercase(Locale.getDefault())?.contains(text) == true) {
temp.add(it)
}
}
recyclerView.adapter?.notifyDataSetChanged()
}
else {
temp.addAll(value)
recyclerView.adapter?.notifyDataSetChanged()
}
return false
}
})
super.onCreateOptionsMenu(menu, inflater)
}
}
adapter class:
class adapter1(var context : Context, var ada : ArrayList<Restaurant_info>) : Adapter<adapter1.viewholderclass>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): viewholderclass {
var view= LayoutInflater.from(parent.context).inflate(R.layout.adapter,parent,false)
return viewholderclass(view)
}
override fun onBindViewHolder(holder: viewholderclass, position: Int) {
var id=ada[position]
holder.name.text=ada[position].name
holder.rating.text=ada[position].rating
holder.cost.text=ada[position].cost_for_one
Picasso.get().load(id.image_url).into(holder.image)
}
override fun getItemCount() :Int{
return ada.size /* returning the size */
}
class viewholderclass(view: View) : RecyclerView.ViewHolder(view) {
var name=view.findViewById<TextView>(R.id.name)
var rating=view.findViewById<TextView>(R.id.rating)
var cost=view.findViewById<TextView>(R.id.price)
var image=view.findViewById<ImageView>(R.id.image)
var layout: RelativeLayout =view.findViewById(R.id.adapter)
}
}
json object:
"data": {
"success": true,
"data": [
{
"id": "1",
"name": "Pind Tadka",
"rating": "4.1",
"cost_for_one": "280",
"image_url": "https://images.pexels.com/photos/1640777/pexels-photo-1640777.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
},
{
"id": "2",
"name": "Garbar Burgers",
"rating": "4.6",
"cost_for_one": "200",
"image_url": "https://images.pexels.com/photos/1639565/pexels-photo-1639565.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
},
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.
I am new in Kotlin MVVM also, I tried to achieved Pagination with legacy approach and stucked in a issue with my RecyclerView, whenever I scroll it the data duplicated, I tried DiffUtils but no help.
I Logged the data in VIEWMODEL class the data is not repeating
but, when I logged in Activity where I am observing it is showing duplicate values
SEARCHRESULTACTIVITY.KT
class SearchResultActivity : AppCompatActivity() {
private lateinit var layoutManager: LinearLayoutManager
private lateinit var recyclerView: RecyclerView
private lateinit var pullAdapter: CustomAdapter
private var pageNumber = 1
private var totalItemsCount = 0
private var firstVisibleItemsCount = 0
private var visibleItemsCount = 0
private var previousTotal = 0
private var loading = true
private var fillPullList: ArrayList<RepoPull> = ArrayList()
private var userName: String = ""
private var repoName: String = ""
private var isEnd = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initialize()
getDataPull(userName, repoName)
loadNextData()
}
private fun initialize() {
setContentView(R.layout.activity_search_result)
recyclerView = findViewById(R.id.repoRecView)
layoutManager = LinearLayoutManager(this)
getSearchQuery()
}
private fun getSearchQuery() {
userName = intent.getStringExtra("owner").toString()
repoName = intent.getStringExtra("repo").toString()
populatePullRv()
}
private fun populatePullRv() {
recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
recyclerView.layoutManager = layoutManager
pullAdapter = CustomAdapter(this, fillPullList)
recyclerView.adapter = pullAdapter
progressBar.visibility = View.VISIBLE
}
private fun loadNextData() {
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val mLayoutManger = recyclerView.layoutManager as LinearLayoutManager
visibleItemsCount = mLayoutManger.childCount
totalItemsCount = mLayoutManger.itemCount
firstVisibleItemsCount = mLayoutManger.findFirstVisibleItemPosition()
if (loading) {
if (totalItemsCount > previousTotal) {
previousTotal = totalItemsCount
pageNumber++
loading = false
progressBar.visibility = View.GONE
}
}
if (!loading && (firstVisibleItemsCount + visibleItemsCount) >= totalItemsCount) {
getDataPull(userName, repoName)
loading = true
Log.d("PAGE", pageNumber.toString())
}
}
})
}
private fun getDataPull(username: String?, reponame: String?) {
val myViewModel = ViewModelProviders.of(this).get(PullVM::class.java)
myViewModel.endofList.observe(this, {
if (it == true) {
isEnd = true
progressBar.visibility = View.GONE
Toast.makeText(this#SearchResultActivity, "All PR Fetched", Toast.LENGTH_SHORT)
.show()
}
})
myViewModel.status.observe(this, {
if (it == false) {
showError(getString(R.string.no_net))
}
})
myViewModel.getPullDataFromVM().observe(this, {
if (it != null) {
listRepos(it) **//DUPLICATE VALUE COMING**
} else {
showError(getString(R.string.nothing_found))
}
})
myViewModel.getPullList(username.toString(), reponame.toString(), pageNumber)
}
private fun showError(s: String) {
progressBar.visibility = View.GONE
val theView =
this#SearchResultActivity.findViewById<View>(android.R.id.content)
Snackbar.make(
theView,
s,
Snackbar.LENGTH_LONG
).show()
}
#SuppressLint("NotifyDataSetChanged")
fun listRepos(repos: List<RepoPull>) {
if (!isEnd) {
progressBar.visibility = View.GONE
fillPullList.addAll(repos)
pullAdapter.notifyDataSetChanged()
}
}}
PULLVM(View Model).kt
class PullVM : ViewModel() {
var pullList: MutableLiveData<List<RepoPull>>
var status = MutableLiveData<Boolean?>()
var endofList = MutableLiveData<Boolean?>()
init {
pullList = MutableLiveData()
}
fun getPullDataFromVM(): MutableLiveData<List<RepoPull>> {
return pullList
}
fun getPullList(ownerName: String, repoName: String, pgNo: Int) {
val retriever = GitHubRetriever
val callback = object : Callback<List<RepoPull>> {
override fun onFailure(call: Call<List<RepoPull>>, t: Throwable) {
status.value = false
}
override fun onResponse(
call: Call<List<RepoPull>>,
response: Response<List<RepoPull>>
) {
if (response.body()?.size == 0) {
endofList.value = true
}
if (response.code() == 404) {
pullList.postValue(null)
} else {
status.value = true
val repos = response.body()
if (repos != null) {
pullList.postValue(repos)
}
}
}
}
retriever.userRepos(
callback,
ownerName,
repoName,
pgNo
)
}
Try moving your viewModel instantiation and observer settings to onCreate so you don't have to create a new viewModel instance and set a new observable to your LiveDatas.
Declare myViewModel as a lateinit property of your Activity and move this part to onCreate
myViewModel = ViewModelProviders.of(this).get(PullVM::class.java)
myViewModel.endofList.observe(this, {
if (it == true) {
isEnd = true
progressBar.visibility = View.GONE
Toast.makeText(this#SearchResultActivity, "All PR Fetched", Toast.LENGTH_SHORT)
.show()
}
})
myViewModel.status.observe(this, {
if (it == false) {
showError(getString(R.string.no_net))
}
})
myViewModel.getPullDataFromVM().observe(this, {
if (it != null) {
listRepos(it) **//DUPLICATE VALUE COMING**
} else {
showError(getString(R.string.nothing_found))
}
})
And
private fun getDataPull(username: String?, reponame: String?)
should only contain
myViewModel.getPullList(username.toString(), reponame.toString(), pageNumber)
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
}
}