简体   繁体   中英

RecyclerView is looping the same data retrieved from firebase

I tried to add a new data to firebase and then show it in a recyclerview, but after i add the data the recyclerview just loop the whole data until the data is done uploading thus creating a view like this: the looped recyclerview

As you can see in the picture that in that link, i tried to add "food 6" data but as the result for the adding process the recyclerview keep updating the items inside it until the adding process complete

Here is my adapter code

class FoodAdapter (private var dataList : ArrayList<Food>): RecyclerView.Adapter<FoodAdapter.MyViewholder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewholder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.food_recyclerview,parent,false)
        return MyViewholder(itemView)
    }

    override fun onBindViewHolder(holder: MyViewholder, position: Int) {
        val currentItem = dataList[position]
        Log.w("adapater",currentItem.image_pic.toString())
        Picasso.get().load(currentItem.image_pic).into(holder.foodPic)
        holder.food_name.text = currentItem.name
        holder.food_price.text = currentItem.price.toString()
        if (currentItem.avail == true){
            holder.food_avail.text = "Tersedia"
            holder.food_avail.setTextColor(Color.GREEN)
        } else {
            if (currentItem.avail == false){
                holder.food_avail.text = "Habis"
                holder.food_avail.setTextColor(Color.RED)
            } else {
                holder.food_avail.text = "Error"
            }
        }

    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    inner class MyViewholder (itemView : View): RecyclerView.ViewHolder(itemView){

        val foodPic : ImageView = itemView.findViewById(R.id.iv_gambar_makanan)
        val food_name : TextView = itemView.findViewById(R.id.tv_nama_makanan)
        val food_avail : TextView = itemView.findViewById(R.id.tv_status_makanan)
        val food_price : TextView = itemView.findViewById(R.id.tv_harga_makanan)
    }

}

here is my update data to firebase code

    private fun addDatatoFirebase() {
        val dataRef = ref.child(preferences.getValue("username").toString()).child("FoodList/"+ UUID.randomUUID().toString())
        var PicUrl = ""
        val addImage = StorageRef.child(preferences.getValue("username").toString())
            .child("food_pics/" + UUID.randomUUID())
        Log.i("Cycle", "Add Image to Firebase")
        addImage.putFile(FilePath).addOnSuccessListener {
            addImage.downloadUrl.addOnSuccessListener {
                PicUrl = it.toString()
                dataRef.child("image_pic").setValue(PicUrl)
            }
        }
        Log.i("URL",addImage.toString())
        dataRef.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                id = snapshot.ref
                Log.w("PicUrl data",PicUrl)
                dataRef.child("name").setValue(food_name)
                dataRef.child("avail").setValue(availability)
                dataRef.child("price").setValue(food_price.toInt())
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT)
            }

        })
    }

and here is the code to get the data

   private fun getFoodData() {
        val foodData = ref.child(preferences.getValue("username").toString()).child("FoodList")
        foodData.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot != null) {
                    for (userSnapshot in snapshot.children) {
                        var data = userSnapshot.getValue(Food::class.java)
                        foodDataArrayList.add(data!!)
                    }
                }
                foodList.adapter = FoodAdapter(foodDataArrayList)
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT)
            }

        })

        foodList.adapter = FoodAdapter(foodDataArrayList)
    }

Can anyone show me how to fix this issue?

You missed out on one thing. Whenever data gets changed, you get all the entries again and again without removing the previous un-updated data. So, the simple solution would be to clear the list before getting the data. Try this code:

private fun getFoodData() {
        val foodData = ref.child(preferences.getValue("username").toString()).child("FoodList")
        foodData.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot != null) {
                    foodDataArrayList.clear() // added this line
                    for (userSnapshot in snapshot.children) {
                        var data = userSnapshot.getValue(Food::class.java)
                        foodDataArrayList.add(data!!)
                    }
                }
                foodList.adapter = FoodAdapter(foodDataArrayList)
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT)
            }

        })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM