Two arrayList in a RecyclerView - arraylist

How can I show both arrayList in the same recycleview.
Debug is correct with the resultado variable.
How can I make the result variable show me in the RecyclerView?
In my activity DetPartido:
val resultado = (response.body()!!.golesLocal)!! + (response.body()!!.golesVisitante)!!
Rv_DetLocal.adapter = DetLocalAdapter(resultado!!)
My adapter:
class DetLocalAdapter(val det_partido: List<Any>): RecyclerView.Adapter<DetLocalAdapter.DetallesViewHolder>() {
private var context: Context? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DetallesViewHolder {
val layoutInflate = LayoutInflater.from(parent.context)
.inflate(R.layout.partido_goles_row, parent, false)
context = parent.context
return DetLocalAdapter.DetallesViewHolder(layoutInflate)
}
override fun onBindViewHolder(holder: DetallesViewHolder, position: Int) {
val itemDetPart = det_partido[position]
holder.bindTiempo(itemDetPart)
holder.itemView.setOnClickListener{
val bundle = Bundle()
bundle.putString(Constants.ID_JUG, itemDetPart.idJugador)
context!!.startActivity(Intent(context, DetPlantilla::class.java).putExtras(bundle))
}
}
override fun getItemCount(): Int {
return det_partido.size
}
class DetallesViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
fun bindTiempo(plantillaModel2: DetLocalModel){
itemView.tv_JugadorLocal.text = plantillaModel2.nombreLocal + "\n Minuto: " + plantillaModel2.minutoLocal
Picasso.get()
.load("https://ffcv.es/ncompeticiones/img/jugadores/" + plantillaModel2.idJugador + ".jpeg")
.fit()
.into(itemView.civ_jugadorLocal)
}
}
}
My model where the arrays are DetPartModel1:
class DetPartModel1{
var golesLocal: ArrayList<DetLocalModel>? = null
var golesVisitante: ArrayList<DetVisiModel>? = null
}
My model where they are golesLocal:
class DetLocalModel (
val idJugador: String,
#SerializedName("nombre")
val nombreLocal: String,
#SerializedName("minuto")
val minutoLocal: String
)
My model where they are golesVisitante:
class DetVisiModel (
val idJugador: String,
#SerializedName("nombre")
val nombreVisi: String,
#SerializedName("minuto")
val minutoVisi: String
)

Your models are same classes , so you can use sealed or just inheritance to differentiate them .
sealed class ModelParent(
val idJugador: String,
#SerializedName("nombre")
val nombreLocal: String,
#SerializedName("minuto")
val minutoLocal: String
)
class DetLocalModel(id : String, number: String, minute: String)
: ModelParent(id,number,minute)
class DetVisiModel(id : String, number: String, minute: String)
: ModelParent(id,number,minute)
class DetPartModel1{
var golesLocal: List<ModelParent> = mutableListOf<DetLocalModel>()
var golesVisitante: List<ModelParent> = mutableListOf<DetVisiModel>()
}
here is how to add them to adapter
create your model:
val model:DetPartModel1 = DetPartModel1(); //todo fill correct data
fill data correctly in your model
add full list to your adapter
Rv_DetLocal.adapter = DetLocalAdapter(mutableListOf<ModelParent>().apply {
addAll(model.golesLocal)
addAll(model.golesVisitante)
})
here is how your adapter must look.
class DetLocalAdapter(val items: List<ModelParent>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
//todo
}
override fun getItemCount(): Int {
items.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = items.get(position)
when(item) {
is DetVisiModel ->holder.bindDetVisiModel()
is DetLocalModel ->holder.bindDetLocalModel()
}
}
}
this is fast solution ,
better way is to have 2 ViewHolder , 2 lists , and differentiate them by viewType

Related

How to delete a record in room database with recyclerview MVVM

I need to delete an item recyclerview adapter which should be notified in room database, please help me in finding a solution and thanks in advance
class ListAdapter : RecyclerView.Adapter<ListAdapter.MyViewHolder>() {
private lateinit var mitemsViewModel: ItemsViewModel
private var itemsList = emptyList<Item>()
private lateinit var item: Item
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_row_layout, parent, false)
)
}
override fun getItemCount(): Int {
return itemsList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
item = itemsList.get(position)
//always remember this technique to save the values in val type
val currentItem = itemsList[position]
holder.itemView.itemNameTV.text = currentItem.itemName.toString()
holder.itemView.itemCodeTV.text = currentItem.itemCode.toString()
holder.itemView.itemCategoryTV.text = currentItem.itemCategory.toString()
holder.itemView.itemDescriptionTV.text = currentItem.itemDescription.toString()
holder.itemView.itemSellingPriceTV.text = currentItem.itemSellingPrice.toString()
holder.itemView.itemStockTV.text = currentItem.itemStock.toString()
holder.itemView.deleteItem.setOnClickListener {
val itName = holder.itemView.itemNameTV.text.toString()
val itCode = holder.itemView.itemCodeTV.text.toString()
val itCategory = holder.itemView.itemCategoryTV.text.toString()
val itDescription = holder.itemView.itemDescriptionTV.text.toString()
val itSellingPrice = holder.itemView.itemSellingPriceTV.text.toString()
val itStock = holder.itemView.itemStockTV.text.toString()
val itime = Item(0, itName, itCode, itCategory, itSellingPrice, itStock, itDescription)
mitemsViewModel.deleteItem(itime)
//dao.deleteItem(itemsList.get(position))
}
}
fun setData(item: List<Item>) {
this.itemsList = item
notifyDataSetChanged()
}}
Help me how to initialize the ViewModel in recyclerview adapter.
The error code after running my app
kotlin.UninitializedPropertyAccessException: lateinit property mitemsViewModel has not been initialized
at com.manju.mobilebilling.ui.items.ListAdapter.onBindViewHolder$lambda-0(ListAdapter.kt:65)
at com.manju.mobilebilling.ui.items.ListAdapter.$r8$lambda$pJauI4KaymNCF6j043M3H3t3CwQ(ListAdapter.kt)
at com.manju.mobilebilling.ui.items.ListAdapter$$ExternalSyntheticLambda0.onClick(D8$$SyntheticClass)
at android.view.View.performClick(View.java:5651)
at android.view.View$PerformClick.run(View.java:22445)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6138)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
You should initialize the ItemsViewModel in the parent Activity or Fragment:
private val viewModel by viewModels<ItemsViewModel>()
Then, instead of passing it directly to the ListAdapter declare a custom click listener and use that as parameter:
// Add a parameter in the adapter
class ListAdapter(
private val clickListener: ListClickListener
) : RecyclerView.Adapter<ListAdapter.MyViewHolder>() {
private var itemsList = emptyList<Item>()
private lateinit var item: Item
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_row_layout, parent, false)
)
}
override fun getItemCount(): Int {
return itemsList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
item = itemsList.get(position)
//always remember this technique to save the values in val type
val currentItem = itemsList[position]
holder.itemView.itemNameTV.text = currentItem.itemName.toString()
holder.itemView.itemCodeTV.text = currentItem.itemCode.toString()
holder.itemView.itemCategoryTV.text = currentItem.itemCategory.toString()
holder.itemView.itemDescriptionTV.text = currentItem.itemDescription.toString()
holder.itemView.itemSellingPriceTV.text = currentItem.itemSellingPrice.toString()
holder.itemView.itemStockTV.text = currentItem.itemStock.toString()
holder.itemView.deleteItem.setOnClickListener {
val itName = holder.itemView.itemNameTV.text.toString()
val itCode = holder.itemView.itemCodeTV.text.toString()
val itCategory = holder.itemView.itemCategoryTV.text.toString()
val itDescription = holder.itemView.itemDescriptionTV.text.toString()
val itSellingPrice = holder.itemView.itemSellingPriceTV.text.toString()
val itStock = holder.itemView.itemStockTV.text.toString()
val itime = Item(0, itName, itCode, itCategory, itSellingPrice, itStock, itDescription)
// Call the click listener
clickListener.onClick(iitem)
}
}
fun setData(item: List<Item>) {
this.itemsList = item
notifyDataSetChanged()
}
}
// Click listener class
class ListClickListener(val clickListener: (item: Item) -> Unit) {
fun onClick(item: Item) = clickListener(item)
}
Finally, declare your ListAdapter in the parent Activity or Fragment with:
val adapter = ListAdapter(ListClickListener { item ->
viewModel.deleteItem(item)
})
Initialize your viewmodel in your activity than pass it via adapter constructor

Show item info on selected item in RecyclerView using Kotlin

I am using kotlin language with android studio. I want to get the properties of the element I clicked in the RecyclerView.
Ben bu kod ile saderc id alabiliyorum
Ex: date
ListAdapter.kt
class ListAdapter(
private val context: Context
) : RecyclerView.Adapter<ListAdapter.ListViewHolder>() {
private var dataList = mutableListOf<Any>()
private lateinit var mListener: onItemClickListener
interface onItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener) {
mListener = listener
}
fun setListData(data: MutableList<Any>) {
dataList = data
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
return ListViewHolder(view)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val question: Questionio = dataList[position] as Questionio
holder.bindView(question)
}
override fun getItemCount(): Int {
return if (dataList.size > 0) {
dataList.size
} else {
return 0
}
}
inner class ListViewHolder(itemView: View, listener: onItemClickListener) :
RecyclerView.ViewHolder(itemView) {
fun bindView(questionio: Questionio) {
itemView.findViewById<TextView>(R.id.txt_policlinic).text = questionio.policlinic
itemView.findViewById<TextView>(R.id.txt_title).text = questionio.title
itemView.findViewById<TextView>(R.id.txt_description).text = questionio.description
itemView.findViewById<TextView>(R.id.txt_date).text = questionio.date
itemView.findViewById<TextView>(R.id.txt_time).text = questionio.time
}
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
}
My code in onCreateView inside list fragment.Edit
ListFragment
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.adapter = adapter
observeData()
adapter.setOnItemClickListener(object : ListAdapter.onItemClickListener {
override fun onItemClick(position: Int) {
showShortToast(position.toString())
}
})
this function is also my observationData(),
I made new edits
private fun observeData() {
binding.shimmerViewContainer.startShimmer()
listViewModel.fetchQuestinData("questions",
requireContext())
.observe(viewLifecycleOwner, {
binding.shimmerViewContainer.startShimmer()
binding.shimmerViewContainer.hideShimmer()
binding.shimmerViewContainer.hide()
adapter.setListData(it)
adapter.notifyDataSetChanged()
})
}
You can pass highOrderFuction into the adapter then setonclickListener for any view you want. Like this:
class ListAdapter(
private val context: Context,
private val onItemClick:(questionio: Questionio)->Unit
) : RecyclerView.Adapter<ListAdapter.ListViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
return ListViewHolder(view,onItemClick)
}
...
inner class ListViewHolder(itemView: View,private val onItemClick:(questionio: Questionio)->Unit) : RecyclerView.ViewHolder(itemView) {
fun bindView(questionio: Questionio) {
//set on any view you want
itemView.findViewById<TextView>(R.id.root_view_id).
setOnClickListener{onItemClick(questionio)}
itemView.findViewById<TextView>(R.id.txt_policlinic).text =
questionio.policlinic
itemView.findViewById<TextView>(R.id.txt_title).text = questionio.title
itemView.findViewById<TextView>(R.id.txt_description).text =
questionio.description
itemView.findViewById<TextView>(R.id.txt_date).text = questionio.date
itemView.findViewById<TextView>(R.id.txt_time).text = questionio.time
}
}
}

How to get data recycleview to parse on other updateactivity?

I have code in ListBukpotAdapter, how can I get data listener.OnClick(currentItem) to parse on other UpdateActivity
Error:
kotlin.UnitializedPropertyAccessExeption: lateinit property listener has not been initialized
class ListBukpotAdapter : RecyclerView.Adapter<ListBukpotAdapter.MyViewHolder>() {
private var bukpotList = emptyList<QrResultBukpot>()
private lateinit var listener: OnAdapterListener
interface OnAdapterListener {
fun OnClick(bukpotDataParsing: QrResultBukpot)
}
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_bukpot, parent, false))
}
override fun getItemCount(): Int {
return bukpotList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = bukpotList[position]
holder.itemView.txtNomorBukpot.text = currentItem.nomorBukpot
holder.itemView.txtNpwpPemotong.text = currentItem.npwpPemotong
holder.itemView.txtMasaPajak.text = currentItem.masaPajak + " / " + currentItem.tahunPajak
holder.itemView.txtMixCode.text = currentItem.mixCode
holder.itemView.rowLayoutBukpot.setOnClickListener {
listener.OnClick(currentItem)
val context = holder.itemView.context
val intent = Intent(context, UpdateBukpotActivity::class.java)
context.startActivity(intent)
}
}
fun setDataBukpot(bukpot: List<QrResultBukpot>){
this.bukpotList = bukpot
notifyDataSetChanged()
}
}
You should initilaze your listener. Your listener variable is lateinit so before you use this, you need to initialize. You can give listener as a constructor parameter from your activity or fragment and can listen interface from your activity or fragment which contains recyclerview.

Unresolved reference: myViewHolder after switching to View Binding

After switching from removing kotlin_extensions and switching to view binding, I received a "Unresolved reference: myViewHolder" in my onBindViewHolder method and when I replace "myViewHolder" with "holder", it then gives me a "Unresolved reference: bind". How do I resolve this.
MyAdapter
class MyAdapter(private val context: Context, private val mHelper : TaskDbHelper) : RecyclerView.Adapter<MyAdapter.MyViewHolder>(),
SwipeAndDragHelper.ActionCompletionContract {
class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
fun binding() {
}
}
private var touchHelper: ItemTouchHelper? = null
private var list = mutableListOf<MyObject>()
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
initList()
super.onAttachedToRecyclerView(recyclerView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(CellCardsBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
#RequiresApi(Build.VERSION_CODES.P)
#SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val myObject = list[position]
myViewHolder.bind(myObject)
val activity: Activity = context as Activity
holder.binding.text.setOnClickListener{
activity.launchActivity<AddNoteActivity>(42) {
putExtra("PositionInList", position.toString())
putExtra("TaskTitle", myObject.title)
putExtra("TaskText", myObject.text)
}
}
activity.findViewById<RecyclerView>(R.id.recyclerView).setOnTouchListener { _, event ->
when (event.actionMasked) {
MotionEvent.ACTION_UP -> {
updateNotesPositionInDb()
false
}
else -> {
false
}
}
}
holder.binding.title.setOnTouchListener { _, event ->
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
touchHelper!!.startDrag(holder)
false
}
else -> {
false
}
}
}
}
private fun initList() {
list.clear()
val db = mHelper.readableDatabase
val cursor = db.query(
TaskContract.TaskEntry.TABLE,
arrayOf(
TaskContract.TaskEntry.ID,
TaskContract.TaskEntry.COL_TASK_TITLE,
TaskContract.TaskEntry.COL_TASK_TEXT,
TaskContract.TaskEntry.COL_TASK_DATE),null, null, null, null, TaskContract.TaskEntry.ID)
while (cursor.moveToNext()) {
val id = cursor.getColumnIndex(TaskContract.TaskEntry.ID)
val idTitle = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE)
val idText = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TEXT)
val idDate = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_DATE)
list.add(MyObject(cursor.getString(id), cursor.getString(idTitle), cursor.getString(idText), cursor.getString(idDate)))
}
notifyDataSetChanged()
cursor.close()
db.close()
}
override fun getItemCount(): Int {
return list.size
}
override fun onViewMoved(oldPosition: Int, newPosition: Int) {
val target = list[oldPosition]
list.removeAt(oldPosition)
list.add(newPosition, target)
notifyItemMoved(oldPosition, newPosition)
}
override fun onViewSwiped(position: Int) {
deleteTask(list[position].ID)
list.removeAt(position)
notifyItemRemoved(position)
updateNotesPositionInDb()
}
fun setTouchHelper(touchHelper: ItemTouchHelper) {
this.touchHelper = touchHelper
}
fun addTask(taskTitle : String, taskText: String) {
val values = ContentValues()
val sdf = SimpleDateFormat("dd/MM/yyyy/", Locale.US)
val date = sdf.format(Date())
values.put(TaskContract.TaskEntry.ID, list.size)
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, taskTitle)
values.put(TaskContract.TaskEntry.COL_TASK_TEXT, taskText)
values.put(TaskContract.TaskEntry.COL_TASK_DATE, date)
val db = mHelper.readableDatabase
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE)
db.close()
list.add(MyObject(list.size.toString(), taskTitle, taskText, date))
notifyItemInserted(list.size)
}
fun addTask() {
val test: Activity = context as Activity
test.launchActivity<AddNoteActivity>(42) {
/* putExtra("user", "854")
p utExtra("user2", "46850") */
}
}
private fun deleteTask(taskId: String) {
val db = mHelper.readableDatabase
db.delete(TaskContract.TaskEntry.TABLE,
"id=$taskId", null)
db.close()
}
fun modifyTask(taskPosition: String, taskTitle: String, taskText: String) {
val target = list[taskPosition.toInt()]
target.title = taskTitle
target.text = taskText
val values = ContentValues()
val sdf = SimpleDateFormat("dd/MM/yyyy/", Locale.US)
val date = sdf.format(Date())
values.put(TaskContract.TaskEntry.ID, taskPosition)
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, taskTitle)
values.put(TaskContract.TaskEntry.COL_TASK_TEXT, taskText)
values.put(TaskContract.TaskEntry.COL_TASK_DATE, date)
val db = mHelper.readableDatabase
db.update(TaskContract.TaskEntry.TABLE,
values, TaskContract.TaskEntry.ID + "=" + target.ID, null)
db.close()
notifyItemChanged(taskPosition.toInt())
}
private fun updateNotesPositionInDb() {
val db = mHelper.readableDatabase
var i = 0
while (i < list.size) {
val values = ContentValues()
values.put(TaskContract.TaskEntry.ID, i)
db.update(TaskContract.TaskEntry.TABLE,
values, TaskContract.TaskEntry.ID + "=? AND " + TaskContract.TaskEntry.COL_TASK_TITLE + "=?", arrayOf(list[i].ID, list[i].title))
i++
}
db.close()
}
I've tried reading Android Studio's official documentation, but it cannot solve my specific problem.
in your class MyViewHolder you have method called binding and you need also to implement it and add paramter
shoud be
class MyViewHolder(private val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
fun bind(data:MyObject) {
binding.yourView=data.title ...
}
}
in onBindViewHolder
..
holder.bind(myObject)
After switching from removing kotlin_extensions and switching to view binding, I received a "Unresolved reference: myViewHolder" in my onBindViewHolder method
Well, your onBindViewHolder method is passing a variable called holder and you're trying to use a variable called myViewHolder, so that seems like a problem.
// --------------------this-----v
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val myObject = list[position]
// v--- doesn't match this
myViewHolder.bind(myObject)
and when I replace "myViewHolder" with "holder", it then gives me a "Unresolved reference: bind". How do I resolve this.
Your MyViewHolder class has a method called binding that takes no arguments. There is no bind method that takes a "myObject".
class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
fun binding() {
}
}
Edit
You should pass an instance of the data class
class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
fun bind(object: MyObject) {
// Set variables on binding
}
}
Then pass an instance from your list via onBindViewHolder:
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val myObject = list[position]
holder.bind(myObject)
Please check this blog post for more.
I got my answer.
class MyAdapter(private val context: Context, private val mHelper : TaskDbHelper) : RecyclerView.Adapter<MyAdapter.MyViewHolder>(),
SwipeAndDragHelper.ActionCompletionContract {
class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
private val titleView: TextView = itemView.findViewById<View>(R.id.title) as TextView
val textView: TextView = itemView.findViewById<View>(R.id.text) as TextView
private val dateTextView: TextView = itemView.findViewById<View>(R.id.date) as TextView
fun binding (myObject: MyObject) {
titleView.text = myObject.title
textView.text = myObject.text
dateTextView.text = myObject.date
}
}
I simply initialised the view I wanted to reference in my layout and called them in the binding() function.

display list view in fragment kotlin

l want display my list view in fragment , l used separated listview adpater .
l got error in class adapter under line val view : View = LayoutInflater.from(context,this).inflate(R.layout.arr_list,parent,false)
class fragment
class fragment_Arr :Fragment(), View.OnClickListener {
override fun onClick(v: View?) {
// val intent = Intent(context, FlightsArrbefor::class.java)
// context!!.startActivity(intent)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_arrivel,container,false)
val url = "xxxxxxxx/airport.json?code=BGW"
Arr().execute(url)
return view
}
inner class Arr : AsyncTask<String, String, String>(){
override fun onPreExecute() {
super.onPreExecute()
}
// for build connection
override fun doInBackground(vararg url: String?): String{
var text : String
val connection = URL(url[0]).openConnection() as HttpURLConnection
try {
connection.connect()
text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }
} finally{
connection.disconnect()
}
return text
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
handleJson(result)
}
override fun onProgressUpdate(vararg text: String?) {
}
#SuppressLint("WrongViewCast")
private fun handleJson (jsonString: String?) {
val jsonObj = JSONObject(jsonString)
val result = jsonObj.getJSONObject("result")
val response = result.getJSONObject("respe")
val airport = response.getJSONObject("airport")
val pluginData = airport.getJSONObject("Data")
val schedule = pluginData.getJSONObject("schedule")
val arrivals = schedule.getJSONObject("arrivals")
// val data = arrivals.getJSONObject("data")
val jsonArray = JSONArray(arrivals.get("data").toString())
val list = ArrayList<FlightShdu>()
var x = 0
while (x < jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(x)
list.add(
FlightShdu(
jsonObject.getJSONObject("flight").getJSONObject("identification").getJSONObject("number").getString("default"),
jsonObject.getJSONObject("flight").getJSONObject("airline").getString("short"),
jsonObject.getJSONObject("flight").getJSONObject("status").getJSONObject("generic").getJSONObject("status" )
)
)
x++
}
list.forEach(::println)
var adapter = ListAdapteArr(this#MainActivity, list)
flight_arrivel_list.adapter = adapter
}
}
List Aadpter Class
class ListAdapteArr (val context: fragment_Arr, var list: ArrayList<FlightShdu>): BaseAdapter() {
#SuppressLint("ViewHolder", "NewApi")
override fun getView(p0: Int, convertView: View?, parent: ViewGroup?): View {
val view : View = LayoutInflater.from(context,this).inflate(R.layout.arr_list,parent,false)
val list = list[p0]
val code = view.findViewById(R.id.code_id) as AppCompatTextView
view.callsign_id.text=list.Callsign
view.airline_id.text=list.Airline
code.text = list.code
view.setOnClickListener {
val intent = Intent(context, FlightDeatilasArr::class.java)
intent.putExtra("Stauts",list.Stauts!!)
intent.putExtra("Callsign",list.Callsign!!)
intent.putExtra("Airline",list.Airline!!)
context!!.startActivity(intent)
}
}
private fun getDateTime(s: String): String? {
try {
val sdf = SimpleDateFormat("EE, MMM d KK:mm a")
val netDate = Date(s.toLong() * 1000)
return sdf.format(netDate)
} catch (e: Exception) {
return e.toString()
}
}
override fun getItem(p0: Int): Any {
return list [p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return list.size
}
}
According to documentation, there is method with single parameter LayoutInflater.html#from(android.content.Context), but you invoke it with 2 parameters
LayoutInflater.from(context,this).inflate(R.layout.arr_list,parent,false)
And by the way, context that you pass is not actually Context, but a fragment
class ListAdapteArr (val context: fragment_Arr, ...)
To fix your problem use next approach
override fun getView(p0: Int, convertView: View?, parent: ViewGroup?): View? {
val view: View = LayoutInflater.from(parent!!.context).inflate(R.layout.arr_list,parent,false)
...
return view
}
According to documentation, parent should never be null.
The parent that this view will eventually be attached to