Android Kotlin:如何从Firebase删除数据 [英] Android Kotlin: How can I delete the data from Firebase

查看:62
本文介绍了Android Kotlin:如何从Firebase删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android Kotlin的新手.单击应用程序上的按钮时,我尝试从Cloud Firebase删除数据.我在适配器上做了一些必要的代码,但是如何在Activity上调用数据库集合?ı在下面分享了我的适配器和我的活动代码.

I am a new about Android Kotlin. I try to delete the data from Cloud Firebase when I click the button on my app. I did some necessary code on my adapter but How can ı call the database collection on my Activity? ı shared the my adapter and my Activity code below.

class NoteAdapter(val titleText: ArrayList<String>, val rowImage: ArrayList<String>, val noteText: ArrayList<String>, val listener: onClick) : RecyclerView.Adapter<NoteAdapter.NoteHolder>() {


    interface onClick {

        fun onItemClickListener(v: View, pos: Int, data: Any)


    }


    class NoteHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val itemImage : ImageView = itemView.findViewById(R.id.recyclerImage)
        val itemDelete: ImageView = itemView.findViewById(R.id.delete)


    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteHolder {

        val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_row, parent, false)
        return NoteHolder(v)
    }

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

        holder.itemView.recyclerTitleText.text = titleText[position]
        Picasso.get().load(rowImage[position]).resize(150,150).into(holder.itemImage)

        holder.itemView.setOnClickListener {


            val intent = Intent(holder.itemView.context, PastNotesActivity:: class.java)
            intent.putExtra("oldTitle", titleText[position])
            intent.putExtra("oldNote", noteText[position])
            intent.putExtra("oldImage", rowImage[position])
            holder.itemView.context.startActivity(intent)


        }

        holder.itemDelete.setOnClickListener { v: View ->

            titleText.removeAt(position)
            noteText.removeAt(position)
            rowImage.removeAt(position)

            notifyItemRemoved(position)

            listener.onItemClickListener(v, position, holder.itemView)
        }

    }

    override fun getItemCount(): Int {

        return titleText.size
    }


    override fun getItemId(position: Int):Long  {
        return position.toLong()
    }

    override fun getItemViewType(position: Int):Int {
        return position
    }


}

这是我的活动代码,我在此活动中创建itemDelete乐趣,但如何在此乐趣中定义适配器代码?我试图写"{id.data}"在我的文档中但是没有用,我应该写什么?

And This is my Activity code, I create the itemDelete fun in this Activity but How can I define my adapter code in this fun? and I tried to write "{id.data}" in my document but did not work what should I write ?

class ListViewActivity : AppCompatActivity() {

    var selectedPicture: Uri? = null

    private  lateinit var auth: FirebaseAuth
    private lateinit var db : FirebaseFirestore

    var titleTextFromFB : ArrayList<String> = ArrayList()
    var noteTextFromFB : ArrayList<String> = ArrayList()
    var imageFromFB : ArrayList<String> = ArrayList()


    var adapter: NoteAdapter? = null



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

        auth = FirebaseAuth.getInstance()
        db = FirebaseFirestore.getInstance()

        getDataFromFirestore()

        // recyclerview

        var layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager

       // adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB)
        //recyclerView.adapter = adapter

        adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB, object: NoteAdapter.onClick{

            override fun onItemClickListener(v: View, pos: Int, data: Any) {

                when(v.id){

                    R.id.delete -> itemDelete(data)

                }

            }

        })

        recyclerView.adapter = adapter

    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {

        val menuInflater = menuInflater
        menuInflater.inflate(R.menu.add_note, menu)

        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        if (item.itemId == R.id.add_note_click) {
            // Take Notes Activity
            val intent = Intent(applicationContext, TakeNotesActivity::class.java)
            intent.putExtra("info","new")
            startActivity(intent)

        } else if (item.itemId == R.id.log_out) {

            val alert = AlertDialog.Builder(this)

            alert.setTitle("Log Out")
            alert.setMessage("Are you sure to logout from the app ?")
            alert.setPositiveButton("Yes") {dialog, which ->

                auth.signOut()
                val intent = Intent(applicationContext, MainActivity::class.java)
                startActivity(intent)
                finish()
            }

            alert.setNegativeButton("No") {dialog, which ->

            }

            alert.show()

        }

        return super.onOptionsItemSelected(item)
    }

    // get data from firestore

    fun getDataFromFirestore() {

        db.collection("Notes").orderBy("date", Query.Direction.DESCENDING).addSnapshotListener{ snapshot, exception ->

            if (exception != null) {

                // If there is a error ,

                Toast.makeText(applicationContext, exception.localizedMessage.toString(), Toast.LENGTH_LONG).show()

            } else {

                if (snapshot != null) {

                    if (!snapshot.isEmpty) {

                        titleTextFromFB.clear()
                        noteTextFromFB.clear()
                        imageFromFB.clear()

                        val documents = snapshot.documents
                        for (document in documents) {

                            val userEmail = document.get("userEmail") as String
                            val noteTitle = document.get("noteTitle") as String
                            val yourNote = document.get("yourNote") as String
                            val downloadUrl = document.get("downloadUrl") as String
                            val timestamp = document.get("date") as Timestamp
                            val date = timestamp.toDate()

                            titleTextFromFB.add(noteTitle)
                            imageFromFB.add(downloadUrl)
                            noteTextFromFB.add(yourNote)

                            adapter!!.notifyDataSetChanged()

                        }
                    }
                }

            }


        }


    }

    fun itemDelete(data: Any) {

        db.collection("Notes").document().delete().addOnSuccessListener {


        }

            .addOnFailureListener { exception ->

                Toast.makeText(applicationContext, exception.localizedMessage.toString(), Toast.LENGTH_LONG).show()
            }
    }


}

推荐答案

此代码无效:

   db.collection("Notes").document().delete().addOnSuccessListener {

db.collection("Notes").document()调用创建对新文档的引用,然后将其删除.所以什么也没发生.

The db.collection("Notes").document() call creates a reference to a new document, which you then delete. So nothing happens.

您需要做的是确定用户单击的文档ID,并将其传递给 document(...)调用.这样可以为正确的文档提供 DocumentReference ,以便 delete()调用随后将删除该文档.

What you need to do is determine the ID of the document that the user clicked on, and pass that into the document(...) call. That gives you a DocumentReference to the correct document, so that the delete() call will then delete that document.

确定用户单击的文档ID的键在以下代码中:

The key to determining the ID of the document the user clicked on is in this code:

adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB, object: NoteAdapter.onClick{
    override fun onItemClickListener(v: View, pos: Int, data: Any) {
        when(v.id){
            R.id.delete -> itemDelete(data)
        }
    }
})

您将需要从以下参数之一确定ID: v post data .通常,我通过在适配器或活动中保留文档ID或 DocumentSnapshot 对象的列表,然后按其位置/索引查找单击的项目来完成此操作.

You will need to determine the ID from one of these parameters: v, post, or data. I typically do this by keeping a list of document IDs or DocumentSnapshot objects in my adapter or activity, and then looking the clicked item up by its position/index.

因此,在您的 getDataFromFirestore 函数中,将快照添加到您在活动类中定义为字段的列表中:

So in your getDataFromFirestore function, add the snapshots to a list that you've defined as a field in your activity class:

// in your activity, declare a list;
var mDocuments: List<DocumentSnapshot>? = null

// Then in getDataFromFirestore store that list
...
mDocuments = snapshot.documents;
val documents = snapshot.documents
for (document in documents) {
    ...
}
...

// And use it when calling itemDelete:
adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB, object: NoteAdapter.onClick{
    override fun onItemClickListener(v: View, pos: Int, data: Any) {
        when(v.id){
            R.id.delete -> itemDelete(mDocuments[pos])
        }
    }
})

// To then finally delete the document by its ID
fun itemDelete(doc: DocumentSnapshot) {
    db.collection("Notes").document(doc.Id).delete()
}

这篇关于Android Kotlin:如何从Firebase删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆