How to delete specific data stored in realtime database in Kotlin?

Viewed 166

I have a problem with delete data from my Firebase Data. When I click on the delete button on one of the notes listed. It deletes all the databases stored in a real-time database. I just want to delete the selected data

This is NoteActivity.kt

class NoteActivity : AppCompatActivity(){

    private var noteId = ""
    private var firebaseUser: FirebaseUser? = null
    private var noteConnector: NoteConnector? = null
    private var noteList: MutableList<Note>? = null


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

        val btn_back = findViewById<Button>(R.id.btn_back)

        btn_back.setOnClickListener({
            startActivity(Intent(this, MenuPage::class.java))
            finish()
        })


        firebaseUser = FirebaseAuth.getInstance().currentUser


        var recyclerView: RecyclerView
        recyclerView = findViewById(R.id.recycler_view_note)
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.reverseLayout = false
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = linearLayoutManager

        noteList = ArrayList()
        noteConnector = NoteConnector( this, noteList as ArrayList<Note>)
        recyclerView.adapter = noteConnector

        displayNote()

        btn_add.setOnClickListener(View.OnClickListener {
            if (editText_note!!.text.toString() == "")
            {
                Toast.makeText(this@NoteActivity, "Please write something here.", Toast.LENGTH_LONG).show()
            }
            else
            {
                addNote()
            }
        })

    }

     private fun addNote() {
        val noteRef = FirebaseDatabase.getInstance().reference.child("Note")
           
        val noteId = noteRef.push().key

        val noteMap = HashMap<String, Any>()
        noteMap["noteID"] = noteId!!
        noteMap["noteDetail"] = editText_note!!.text.toString()
        noteMap["notePublisher"] = firebaseUser!!.uid

        noteRef.child(noteId).updateChildren(noteMap)

        Toast.makeText(this, "Task is added successfully.", Toast.LENGTH_LONG).show()

   
        editText_note!!.text.clear()
    }

    private fun displayNote()
    {
        val noteRef = FirebaseDatabase.getInstance().reference
            .child("Note")
            .child(noteId)

        noteRef.addValueEventListener(object : ValueEventListener
        {
            override fun onDataChange(p0: DataSnapshot)
            {
                if (p0.exists())
                {
                    noteList!!.clear()

                    for (snapshot in p0.children)
                    {
                        val note = snapshot.getValue(Note::class.java)
                        noteList!!.add(note!!)
                    }

                    noteConnector!!.notifyDataSetChanged()
                }
            }

            override fun onCancelled(p0: DatabaseError) {
            }
        })
    }

}

This is NoteConnector.kt

class NoteConnector(
    private val mContext: Context,
    private val mNote: MutableList<Note>
) : RecyclerView.Adapter<NoteConnector.ViewHolder>() {

    private var firebaseUser:  FirebaseUser? = null
    private var noteId = ""

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteConnector.ViewHolder
    {
        val view = LayoutInflater.from(mContext).inflate(R.layout.note_page, parent, false)
        return ViewHolder(view)
    }

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

    override fun onBindViewHolder(holder: NoteConnector.ViewHolder, position: Int)
    {
        firebaseUser = FirebaseAuth.getInstance().currentUser

        val note = mNote!![position]

        holder.viewNote.text = note.getNoteDetail()

        holder.buttonDelete.setOnClickListener {
            deleteNote()

            mNote.remove(note)
            notifyDataSetChanged()
        }

    }

    private fun deleteNote() {

        FirebaseDatabase.getInstance().getReference("Note")
            .child(noteId!!)
            .removeValue()


        Toast.makeText(mContext,"Deleted", Toast.LENGTH_LONG).show()
    }


    //access note
    inner class ViewHolder (@NonNull itemView: View) : RecyclerView.ViewHolder(itemView)
    {

        var viewNote : TextView
        var buttonDelete : ImageView

        init {
            viewNote = itemView.findViewById(R.id.text_on_note)
            buttonDelete = itemView.findViewById(R.id.button_task_delete)

        }
    }

image database edited

Can someone help me to solve this problem? Thank you.

1 Answers

The problem is that you define noteId as:

private var noteId = ""

And never give it a value. When you then call:

FirebaseDatabase.getInstance().getReference("Note")
    .child(noteId!!)
    .removeValue()

It deletes /Note/, so it deletes all notes.

You will need to ensure that noteId is set to the key of the note you want to delete.

I'd typically do this by passing the key into your deleteNote function when you call it:

private fun deleteNote(String noteId) {
    FirebaseDatabase.getInstance().getReference("Note")
        .child(noteId!!)
        .removeValue()

    Toast.makeText(mContext,"Deleted", Toast.LENGTH_LONG).show()
}

And then you call it with something like this:

holder.buttonDelete.setOnClickListener {
    deleteNote(node.id) // this needs to be the key of the note that the user clicked on

    mNote.remove(note)
    notifyDataSetChanged()
}
Related