App/Android Native

Clone project - Book App - Step 3 (update/delete book info)

Agrafenaaa 2021. 11. 1. 21:49

결과화면

 

 

I EDIT

1. AdapterPdfAdmin - onBindViewHolder

2. AdapterPdfAdmin - moreOptionDialog

    private fun moreOptionsDialog(model: ModelPdf, holder: AdapterPdfAdmin.HolderPdfAdmin) {
        //get id, url, title of the selected book
        val bookId = model.id
        val bookUrl = model.url
        val bookTitle = model.title

        //option dialog
        val options = arrayOf("Edit", "Delete")
        //alert
        val builder = AlertDialog.Builder(context)
        builder.setTitle("Select")
            .setItems(options){ dialog, position ->
                if(position==0){
                    //edit
                    val intent = Intent(context, PdfEditActivity::class.java)
                    intent.putExtra("bookId", bookId)
                    context.startActivity(intent)
                }else if(position==1){
                    //delete
                    MyApplication.deleteBook(context, bookId, bookUrl, bookTitle)
                }
            }
            .show()
    }

3. PdfEditActivity - loadCategories, loadBookInfo 

수정 여부와 상관 없이 선택한 책의 기존 정보 불러오기

 private fun loadBookInfo() {
        Log.d(TAG, "loadBookInfo: Loading book info")
        val ref = FirebaseDatabase.getInstance().getReference("Books")
        ref.child(bookId)
            .addListenerForSingleValueEvent(object: ValueEventListener{
                override fun onDataChange(snapshot: DataSnapshot) {
                    // get book info
                    selectedCategoryId = snapshot.child("categoryId").value.toString()
                    val description = snapshot.child("description").value.toString()
                    val title = snapshot.child("title").value.toString()

                    // set to views
                    binding.titleEt.setText(title)
                    binding.descriptionEt.setText(description)

                    // load book category info
                    Log.d(TAG, "onDataChange: Loading book categoryId")
                    val refBookCategory = FirebaseDatabase.getInstance().getReference("Categories")
                    refBookCategory.child(selectedCategoryId)
                        .addListenerForSingleValueEvent(object: ValueEventListener{
                            override fun onDataChange(snapshot: DataSnapshot) {
                                // get category
                                val category = snapshot.child("category").value
                                // set to tv
                                binding.categoryTv.text = category.toString()
                            }
                            override fun onCancelled(error: DatabaseError) {
                            }
                        })
                }
                override fun onCancelled(error: DatabaseError) {
                }
            })
    }

4. PdfEditActivity - validateData()

 private var title = ""
    private var description = ""
    private fun validateData() {
        // get data from views
        title = binding.titleEt.text.toString().trim()
        description = binding.descriptionEt.text.toString().trim()
        // validate data
        if (title.isEmpty()) {
            Toast.makeText(this, "Enter title", Toast.LENGTH_SHORT).show()
        } else if (description.isEmpty()) {
            Toast.makeText(this, "Enter description", Toast.LENGTH_SHORT).show()
        } else if (selectedCategoryId.isEmpty()) {
            Toast.makeText(this, "Select category", Toast.LENGTH_SHORT).show()
        } else {
            updatePdf()
        }
    }

4. PdfEditActivity - updatePdf()

 //setup data to update in db
        val hashMap = HashMap<String, Any>()
        hashMap["title"] = "$title"
        hashMap["description"] = "$description"
        hashMap["categoryId"] = "$selectedCategoryId"

        //start updating
        val ref = FirebaseDatabase.getInstance().getReference("Books")
        ref.child(bookId)
            .updateChildren(hashMap)
            .addOnSuccessListener {
                progressDialog.dismiss()
                Log.d(TAG, "updatePdf: updated book info successfully")
                Toast.makeText(this, "Updated book info successfully", Toast.LENGTH_SHORT).show()
            }
            .addOnFailureListener { e ->
                progressDialog.dismiss()
                Log.d(TAG, "updatePdf: Failed to update book info. Error: ${e.message}")
                Toast.makeText(this, "Failed to update book info. Error: ${e.message}", Toast.LENGTH_SHORT).show()
            }

 

 

II DELETE

1. MyApplication - deleteBook(Context, bookId, bookUrl, bookTitle)

Context : progressDialog 설정용

bookId: realtime DB 삭제용

bookUrl: storage 삭제용

booktitle: progressDialog 메시지용

🔥 storage와 db 각 삭제해야 완전한 삭제 가능

val storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(bookUrl)
            storageReference.delete()
                .addOnSuccessListener {
                    Log.d(TAG, "deleteBook: deleted from firebase storage")
                    // additionally remove from realtime db
                    Log.d(TAG, "deleteBook: deleting from firebase db")
                    val ref = FirebaseDatabase.getInstance().getReference("Books")
                    ref.child(bookId)
                        .removeValue()
                        .addOnSuccessListener {
                            progressDialog.dismiss()
                            Log.d(TAG, "deleteBook: deleted from db.")
                            Toast.makeText(
                                context, "deleteBook: deleted from db", Toast.LENGTH_SHORT).show()
                        }
                        .addOnFailureListener { e ->
                            progressDialog.dismiss()
                            Log.d(TAG, "deleteBook: failed to delete from db. Error: ${e.message}")
                            Toast.makeText(
                                context, "deleteBook: failed to delete from db. Error: \${e.message}", Toast.LENGTH_SHORT).show()
                        }
                }
                .addOnFailureListener { e ->
                    Log.d(TAG, "deleteBook: failed to delete from storage. Error: ${e.message}")
                    Toast.makeText(
                        context, "deleteBook: failed to delete from storage. Error: \${e.message}", Toast.LENGTH_SHORT).show()
                }

 

 

Debugging

1. Firestorage metadata bytes 크기 측정

 

 

 

 

느낀점: DataSnapshot에 대한 개념 확고히 할 것 

 

 

 

 

 

 

 

 

Ref: https://www.youtube.com/channel/UCT132T980-1lhm0hcZFy4ZA