Kotlin RecyclerView,在加载项目到 RecyclerView 中遇到问题。

huangapple go评论65阅读模式
英文:

Kotlin RecyclerView, having issue with loading the items into the recyclerview

问题

I see you have shared a portion of your Android application's code for handling a RecyclerView and Adapter. However, you mentioned that you're facing an issue, but it's not clear what the specific problem is. If you could provide more details about the problem you're encountering or the specific error messages, I would be happy to assist you further.

英文:

so currently i'm using this code to get the data from oracle and save it into a data class and from the data class i put it in the recyclercview using the adapter here are the parts of the code,

Adapter:\package com.example.mobileappv2
import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.TextViewimport androidx.recyclerview.widget.RecyclerViewimport com.example.mobileappv2.ui.dashboard.scannedCodes

class FoodMenuAdapter(private val menuItems: ArrayList<BookRecord>) : RecyclerView.Adapter<FoodMenuAdapter.ViewHolder>() {

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    // Define properties for each view in your custom layout
    val ItemNum: TextView = itemView.findViewById(R.id.ItemNum)
    val ItemDescription: TextView = itemView.findViewById(R.id.ItemDescription)
    val OPNum: TextView = itemView.findViewById(R.id.OPNum)
    val LotNumber: TextView = itemView.findViewById(R.id.LotNumber)
    val PickQuantity: TextView = itemView.findViewById(R.id.PickQuantity)
    val StockLocation: TextView = itemView.findViewById(R.id.StockLocation)
    val PcsMissing: TextView = itemView.findViewById(R.id.PcsMissing)
    val buttonPL: Button = itemView.findViewById(R.id.buttonPL)

}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    // Inflate the custom layout for the food menu item
    val itemView = LayoutInflater.from(parent.context).inflate(R.layout.picklistsetup, parent, false)
    return ViewHolder(itemView)

}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    val menuItem = menuItems[position]

    // Set the data from the current item to the respective views
    holder.ItemNum.text = menuItem.item
    holder.ItemDescription.text = menuItem.description
    holder.OPNum.text = menuItem.OPNum
    holder.LotNumber.text = menuItem.LotNumber
    holder.PickQuantity.text = menuItem.PickQuantity
    holder.StockLocation.text = menuItem.StockLocation
    holder.PcsMissing.text = menuItem.PcsMissing

    // Set click listener for the button
    holder.buttonPL.setOnClickListener {

        val bookingID = menuItem.bookingId
        scannedCodes.add(bookingID.toString())

    }

}

override fun getItemCount(): Int {

    return menuItems.size

}

}

Layout for the recycler view:

\<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="wrap_content"tools:ignore="MissingDefaultResource">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/ItemDescription"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="50dp"
android:text=""
android:textSize="12sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ItemNum"
tools:ignore="TextSizeCheck" />
<TextView
android:id="@+id/LotNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="50dp"
android:text=""
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/OPNum" />
<TextView
android:id="@+id/StockLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="50dp"
android:text=""
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/PickQuantity" />
<TextView
android:id="@+id/PcsMissing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="50dp"
android:text=""
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/StockLocation" />
<TextView
android:id="@+id/OPNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="50dp"
android:text=""
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ItemDescription" />
<TextView
android:id="@+id/ItemNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="60dp"
android:text=""
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/PickQuantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="50dp"
android:text=""
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/LotNumber" />
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="Pcs Missing:"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView6" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="Lot Number:"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="Pick Quantity:"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView5" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="Stock Locator:"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView4" />
<Button
android:id="@+id/buttonPL"
android:layout_width="181dp"
android:layout_height="59dp"
android:layout_marginTop="64dp"
android:text="Scan and Book"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/PcsMissing" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="35dp"
android:layout_marginTop="60dp"
android:text="Item Number:"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="Item Description:"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="OP Number:"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

Layout in which the recyclerview is in:

`\<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".ui.notifications.NotificationsFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<TextView
android:id="@+id/text_notifications"
android:layout_width="0sp"
android:layout_height="0sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
```
```
</androidx.constraintlayout.widget.ConstraintLayout>`
````

calling the adapter from the recyclerview fragment:

***
```
\package com.example.mobileappv2.ui.notifications
```
```
import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport androidx.fragment.app.Fragmentimport androidx.lifecycle.ViewModelProviderimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerViewimport com.example.mobileappv2.BookRecordimport com.example.mobileappv2.FoodMenuAdapterimport com.example.mobileappv2.databinding.FragmentNotificationsBinding
```
```
class NotificationsFragment : Fragment() {
```
```
private var _binding: FragmentNotificationsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val notificationsViewModel =
ViewModelProvider(this).get(NotificationsViewModel::class.java)
_binding = FragmentNotificationsBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textNotifications
notificationsViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
val recyclerView: RecyclerView = binding.recyclerView
val menuItems = ArrayList<BookRecord>()
val adapter = FoodMenuAdapter(menuItems)
val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) // Set the layout manager
layoutManager.scrollToPosition(0)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
```
```
}``
```

getting the data from the home page:

  import android.annotation.SuppressLintimport android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.EditTextimport android.widget.TextViewimport android.widget.Toastimport androidx.fragment.app.Fragmentimport androidx.lifecycle.ViewModelProviderimport com.example.mobileappv2.BookRecordimport com.example.mobileappv2.Rimport com.example.mobileappv2.bookRecordsimport com.example.mobileappv2.databinding.FragmentHomeBindingimport org.jsoup.Jsoupimport org.jsoup.parser.Parserimport java.io.BufferedReaderimport java.io.InputStreamReaderimport java.net.HttpURLConnectionimport java.net.URL
private val Picklist = mutableListOf<String>()private const val PhoneLocation = "MAIN STORES"
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textHome
homeViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
val sendbutton = binding.sendButton
sendbutton.setOnClickListener{
sendPinandjobnumber()
}
return root
}
@SuppressLint("InflateParams")
private fun sendPinandjobnumber() {
val navHome = layoutInflater.inflate(R.layout.fragment_home, null)
val test = navHome.findViewById<TextView>(R.id.test)
val jobnum = binding.root.findViewById<EditText>(R.id.JOBNum).text
Picklist.add(jobnum.toString())
val pin = binding.root.findViewById<EditText>(R.id.PINNum).text
Picklist.add(pin.toString())
Picklist.add(PhoneLocation)
if (Picklist.isNotEmpty()) {
Thread {
try {
// HTTP POST request to send the data to the php
val url = URL("Used to connect to the oracle database")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.doOutput = true
val postData = "data=${Picklist.joinToString(",")}"
val writer = connection.outputStream.bufferedWriter()
writer.write(postData)
writer.flush()
val responseCode = connection.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
// Read the response from the php
val inputStream = connection.inputStream
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
val response = bufferedReader.readLine()
requireActivity().runOnUiThread() {
test.text = Picklist.toString()
Toast.makeText(requireContext(), "Data was sent", Toast.LENGTH_LONG).show()
val xmlDoc = Jsoup.parse(response, "", Parser.xmlParser())
val recordElements = xmlDoc.select("BOOKRECORD")
for (recordElement in recordElements) {
val bookingId = recordElement.selectFirst("BOOKING_ID")?.text()
val ItemNum = recordElement.selectFirst("ITEM")?.text()
val ItemDescription = recordElement.selectFirst("DESCRIPTION")?.text()
val OPNum = recordElement.selectFirst("UOM")?.text()
val LotNumber = recordElement.selectFirst("LOT_NUMBER")?.text()
val PickQuantity = recordElement.selectFirst("OPENQTY")?.text()
val StockLocation = recordElement.selectFirst("STOCKLOCATOR")?.text()
val PcsMissing = recordElement.selectFirst("MISSING")?.text()
val bookRecord = BookRecord(bookingId, ItemNum, ItemDescription, OPNum, LotNumber, PickQuantity, StockLocation, PcsMissing)
bookRecords.add(bookRecord)
}
}
} else {
val errorMessage = "HTTP error: ${connection.responseMessage}"
requireActivity().runOnUiThread {
Toast.makeText(
requireContext(),
errorMessage,
Toast.LENGTH_LONG
).show()
}
}
}
catch (e: Exception) {
val errorMessage = "Error: ${e.message}"
requireActivity().runOnUiThread {
Toast.makeText(requireContext(), errorMessage, Toast.LENGTH_LONG).show()
}
}
}.start()
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}```
i tried moving the call for the adapter and such from one fragment to another and to the main activity aswell and i even put toasts to make sure everything was loading and such i don't get any errors when i go to the notification fragment and sadly i don't get the list either
</details>
# 答案1
**得分**: 0
以下是翻译好的内容:
诚挚地说,我从不将RecyclerView逻辑放在`onCreateView()`中,因为它只负责获取绑定和填充布局。
尝试将RecyclerView的所有逻辑从`onCreateView()`移至`onViewCreated()`中。
在`onViewCreated()`中也可以访问绑定。
虽然没有测试,但你应该有类似以下的代码:
```kotlin
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)
val homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
val textView: TextView = binding.textHome
homeViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
val sendbutton = binding.sendButton
sendbutton.setOnClickListener{
sendPinandjobnumber()
}
}

如果这解决了你的问题,请告诉我。如果没有,请评论,我将提供更多支持。祝编程愉快!

英文:

Sincerly, I never put RecyclerView logic in onCreateView() since it's only responsible to get the binding and inflate your layout.

Try moving all the logic for RecyclerView from onCreateView() to onViewCreated().

Binding is also accessible in onViewCreated().

Didn't tested but you should have something like this:

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)
val homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
val textView: TextView = binding.textHome
homeViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
val sendbutton = binding.sendButton
sendbutton.setOnClickListener{
sendPinandjobnumber()
}
}

Let me know if this solved your problem, if not, comment and I will provide more support, happy coding!

huangapple
  • 本文由 发表于 2023年6月8日 16:15:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定