ESP32, ИНТЕГРИРОВАННЫЙ СО СКАНЕРОМ ШТРИХ-КОДА И ПРИЛОЖЕНИЕМ ДЛЯ Android, позволяет удалять элементы из RecyclerView и FiAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 ESP32, ИНТЕГРИРОВАННЫЙ СО СКАНЕРОМ ШТРИХ-КОДА И ПРИЛОЖЕНИЕМ ДЛЯ Android, позволяет удалять элементы из RecyclerView и Fi

Сообщение Anonymous »

Я хочу удалить элемент из RecyclerView и Firebase, когда нажимаю кнопку удаления. мой код здесь MainActivity.kt

Код: Выделить всё

class MainActivity : AppCompatActivity() {

private lateinit var recyclerView: RecyclerView
private lateinit var adapter: ItemAdapter
private lateinit var items: MutableList
private lateinit var database: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.item_main)

// Initialize RecyclerView
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
items = mutableListOf()
adapter = ItemAdapter(items, this)
recyclerView.adapter = adapter

hideSystemUI()

// Initialize Firebase database reference
database = FirebaseDatabase.getInstance().getReference("scannedItems")

// Fetch product data from Firebase
fetchScannedItems()

// Set listener for system UI visibility changes
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
if ((visibility and View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
hideSystemUI()
}
}
}

// Function to fetch product data from Firebase
// MainActivity.kt
private fun fetchScannedItems() {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
items.clear()  // Clear list to avoid duplicates
for (productSnapshot in snapshot.children) {
val product = productSnapshot.getValue(ProductData::class.java)
product?.let { items.add(it) }  // Add product to list if not null
}
Log.d("MainActivity", "Fetched items: $items")
adapter.notifyDataSetChanged()  // Update RecyclerView
}

override fun onCancelled(error: DatabaseError) {
Log.w("MainActivity", "loadPost:onCancelled", error.toException())
}
})
}

// Listen for changes in scanned items in Firebase and update RecyclerView

// Hide the system UI (e.g., status bar and navigation bar)
private fun hideSystemUI() {
val decorView = window.decorView
decorView.systemUiVisibility = (
View.SYSTEM_UI_FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
)
}

override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
hideSystemUI()
}
}

}

мой ItemAdapter.kt

Код: Выделить всё

class ItemAdapter(private var items: MutableList
, private val context: Context) : RecyclerView.Adapter() {

inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemNameTextView: TextView = itemView.findViewById(R.id.txtView_itemName)
val itemPriceTextView: TextView = itemView.findViewById(R.id.txtView_Price)
val qtyTextView: TextView = itemView.findViewById(R.id.txtView_qty)
val deleteButton: ImageButton = itemView.findViewById(R.id.btn_delete)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ItemViewHolder(view)

}

override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val product = items[position]  // Corrected variable name to 'product' to align with usage
holder.itemNameTextView.text = product.productName
holder.itemPriceTextView.text = "₱${product.productPrice}"
holder.qtyTextView.text = "Qty: ${product.qty}"

holder.deleteButton.setOnClickListener{
deleteItem(position)
}
}

private fun deleteItem(position: Int) {
// Handle case if the item is already removed or invalid position
if (position <  0 || position >= items.size) {
return
}

val product = items[position]
val productBarcode = product.productBarcode

// Firebase reference
val itemRef = FirebaseDatabase.getInstance().getReference("scannedItems").child(productBarcode)

// Remove the item from Firebase
itemRef.removeValue()
.addOnSuccessListener {
// Successfully removed from Firebase
items.removeAt(position) // Remove the item from the list in memory

// Notify the adapter that the item was removed
notifyItemRemoved(position)

// If the list is empty, show a message or handle UI changes accordingly
if (items.isEmpty()) {
// Optionally, hide the RecyclerView or show an empty view
Toast.makeText(context, "No items left", Toast.LENGTH_SHORT).show()
// If needed, set RecyclerView visibility to GONE or update the UI accordingly
// recyclerView.visibility = View.GONE
} else {
// Update the remaining items in the list
notifyItemRangeChanged(position, items.size)
}
}
.addOnFailureListener { exception ->
// Handle error if the removal failed
Toast.makeText(context, "Failed to remove item: ${exception.message}", Toast.LENGTH_LONG).show()
}
}

override fun getItemCount(): Int = items.size
}

и мой ProductData.kt

Код: Выделить всё

package com.example.negeshoca

data class ProductData(
val productBarcode: String = "",
val productName: String = "",
val productPrice: Double = 0.0,
val qty : Int = 1

)

все работает нормально, но в происходящем есть одна загвоздка. Дело в том, что когда есть несколько элементов (скажем, 3 элемента в recyclerview в моем сценарии), когда я удаляю первый элемент в списке, его данные также будут удалены из Firebase в разделе «/scannedItems», но второй элемент также будет удалено вместе с первым элементом из recyclerview (но данные второго элемента останутся в Firebase). Последний элемент остается в recyclerview. Далее, когда второй элемент удаляется, то же самое происходит с последним элементом. Наконец, всякий раз, когда я удаляю последний элемент в представлении recyclerview, приложение закрывается.

Подробнее здесь: https://stackoverflow.com/questions/791 ... from-recyc
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»