Kotlin firebase удаление данных

Android Kotlin: How can I delete the data from Firebase

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, val rowImage: ArrayList, val noteText: ArrayList, val listener: onClick) : RecyclerView.Adapter() < 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 >> 

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 «» 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= ArrayList() var noteTextFromFB : ArrayList = ArrayList() var imageFromFB : ArrayList = 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") auth.signOut() val intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) finish() > alert.setNegativeButton("No") > 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() > > > 

Источник

Читайте также:  Настройка виртуальной среды python

How to delete from firebase realtime database?

enter image description here

I am using Firebase realtime database in Android app, and have data like this: How can i delete the record «Apple» (marked in picture)? According to the docs, to remove an item you call removeValue() on the reference. But to get the reference i require the child id. Because its a random generated id (-KISNx87aYigsH3ILp0D), how to delete it?

7 Answers 7

If you don’t know the key of the items to remove, you will first need to query the database to determine those keys:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); Query applesQuery = ref.child("firebase-test").orderByChild("title").equalTo("Apple"); applesQuery.addListenerForSingleValueEvent(new ValueEventListener() < @Override public void onDataChange(DataSnapshot dataSnapshot) < for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) < appleSnapshot.getRef().removeValue(); >> @Override public void onCancelled(DatabaseError databaseError) < Log.e(TAG, "onCancelled", databaseError.toException()); >>); 

I think, you wrote that part getInstance().ref() accidently. That code should be FirebaseDatabase.getInstance().getReference();

 mPostReference = FirebaseDatabase.getInstance().getReference() .child("quotes").child(mPostKey); mPostReference.removeValue(); 

If you are using firebase-admin you can simply try this out as

And also do remember to use async and await syntax.

onDeletePost(id:string)< return this.http.delete(`https://my-angular8-prjt.firebaseio.com/posts/$.json`).subscribe(); > 

Depending on how and why you are deleting the data you can use these:

// Could store the push key or get it after push String newPostKey = yourDatabase.child('firebase-test').push(< something:something >).key(); // Depends how you get to here howYouGotHereId.parent().setValue(null); 

Assume that images is the directory of your firebase database which you want to clear.

private static DatabaseReference mDatabase; public static void clearData()

Here images is the parent directory of the database. If you want to clear a nested directory (DCIM) inside the images directory so that you can retain the remaining data in it.

In that scenario you can do like this,

mDatabase = FirebaseDatabase.getInstance().getReference(); mDatabase.child("images").child("DCIM").setValue(null); 

As a response to the query, Please try to use setValue method with null value setValue(null) to clear the data from firebase database

Источник

How to remove items from firebase RecyclerView

I’m currently working on Adding Friends with the help of firebase RecyclerView in which if a user tap on ADD button, he is added in database n that tapped item is needed to be removed permanently.. so, how to achieve it through firebase model as we dont have any data list to remove from.. Here’s the code

 @Override public void onStart() < super.onStart(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); EmailPref=prefs.getString("EmailPref", EmailPref); if(EmailPref!=null)< final Firebase ref = new Firebase(constants.FIREBASE_URL+"rootssahaj/authGplus"); FirebaseRecyclerAdapteradapter=new FirebaseRecyclerAdapter( FriendsData.class, R.layout.chat_view_list, FriendsViewHolder.class, ref ) < @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void populateViewHolder(FriendsViewHolder friendsViewHolder, FriendsData s, int position) < String key = this.getRef(position).getKey(); Log.e("SahajLOG", "String Keyyy " + key + " n EmailPref" + EmailPref); if (!Objects.equals(key, EmailPref)) < friendsViewHolder.mName.setText(s.getUserNAME()); Picasso.with(context).load(s.getPicurl()).transform(new CircleTransform()).into(friendsViewHolder.mImageProfile); String keylocal = key; Log.e("pavan", "Populate AddF key" + keylocal+" " + position); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); prefs.getString("keylocal" + position, keylocal + position); if (keylocal != null) < prefs.edit().putString("keylocal" + position, keylocal + position).commit(); >> else < friendsViewHolder.mCardView.setVisibility(View.GONE); //friendsViewHolder.setVisibility(View.GONE); >> >; recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setItemAnimator(new SlideInLeftAnimator()); recyclerView.getItemAnimator().setAddDuration(1000); recyclerView.getItemAnimator().setRemoveDuration(1000); recyclerView.getItemAnimator().setMoveDuration(1000); recyclerView.getItemAnimator().setChangeDuration(1000); SlideInLeftAnimator animator = new SlideInLeftAnimator(); animator.setInterpolator(new OvershootInterpolator()); recyclerView.setItemAnimator(animator); AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(adapter); alphaAdapter.setDuration(500); alphaAdapter.setInterpolator(new OvershootInterpolator(.5f)); alphaAdapter.setFirstOnly(false); recyclerView.setAdapter(new ScaleInAnimationAdapter(alphaAdapter)); > > public class FriendsViewHolder extends RecyclerView.ViewHolder < ImageView mImageProfile; android.widget.TextView mName; private int mVisibility; Boolean CallAdd=false; Button mAdd; String keylocal; CardView mCardView; public FriendsViewHolder(View itemView) < super(itemView); mCardView=(CardView)itemView.findViewById(R.id.cardView); mImageProfile=(ImageView)itemView.findViewById(R.id.profilePICC); mName=(android.widget.TextView)itemView.findViewById(R.id.NameUSER); context = itemView.getContext(); mAdd=(Button)itemView.findViewById(R.id.addButton); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if(prefs.getBoolean("CallAdd", CallAdd))< AddaddButton(); >mAdd.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); EmailPref = prefs.getString("EmailPref", EmailPref); keylocal=prefs.getString("keylocal"+getAdapterPosition(),keylocal+getAdapterPosition()); final Firebase mFirebaseRef = new Firebase(constants.FIREBASE_URL + "rootssahaj/authGplus/"+ EmailPref); mFirebaseRef.child("friends").child(keylocal).setValue("true"); Log.e("pavan", "Chat Adapter " + EmailPref + keylocal + " final key: " + keylocal); //remove(getAdapterPosition()); >>); > public void AddaddButton() < if (mAdd.getVisibility() == View.INVISIBLE) < mAdd.setVisibility(View.VISIBLE); >> > 

Источник

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

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? = null override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_note) val btn_back = findViewById(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) 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() 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) < >>) > > 
class NoteConnector( private val mContext: Context, private val mNote: MutableList ) : RecyclerView.Adapter() < 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.

Источник

Delete data from Cloud Firestore

The following examples demonstrate how to delete documents, fields, and collections.

Delete documents

To delete a document, use the following language-specific delete() methods:

Web modular API

Web namespaced API

Swift
Objective-C

Use the deleteDocumentWithCompletion: method:

Kotlin+KTX

Java

Dart

Java
Python

Python

C++
Node.js
Go
PHP
Unity

Use the DeleteAsync() method:

DocumentReference cityRef = db.Collection("cities").Document("DC"); cityRef.DeleteAsync();
C#

Use the DeleteAsync() method:

Ruby

When you delete a document, Cloud Firestore does not automatically delete the documents within its subcollections. You can still access the subcollection documents by reference. For example, you can access the document at path /mycoll/mydoc/mysubcoll/mysubdoc even if you delete the ancestor document at /mycoll/mydoc .

Non-existent ancestor documents appear in the console, but they do not appear in query results and snapshots.

If you want to delete a document and all the documents within its subcollections, you must do so manually. For more information, see Delete Collections.

Delete fields

To delete specific fields from a document, use the following language-specific FieldValue.delete() methods when you update a document:

Web modular API

Use the deleteField() method:

Web namespaced API

Use the FieldValue.delete() method:

Swift

Use the FieldValue.delete() method:

Objective-C

Use the fieldValueForDelete: method:

Kotlin+KTX

Use the FieldValue.delete() method:

Java

Use the FieldValue.delete() method:

Dart

Use the FieldValue.delete() method:

Java

Use the FieldValue.delete() method:

Python

Use the firestore.DELETE_FIELD method:

Python

Use the firestore.DELETE_FIELD method:

C++

Use the FieldValue::Delete() method:

Node.js

Use the FieldValue.delete() method:

Go

Use the firestore.Delete method:

PHP

Use the FieldValue::deleteField() method:

Unity

Use the FieldValue.Delete method:

DocumentReference cityRef = db.Collection("cities").Document("BJ"); Dictionary updates = new Dictionary  < < "Capital", FieldValue.Delete >>;
C#

Use the FieldValue.Delete method:

Ruby

Use the firestore.field_delete method:

Delete collections

To delete an entire collection or subcollection in Cloud Firestore, retrieve (read) all the documents within the collection or subcollection and delete them. This process incurs both read and delete costs. If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors. Repeat the process until you’ve deleted the entire collection or subcollection.

Deleting a collection requires coordinating an unbounded number of individual delete requests. If you need to delete entire collections, do so only from a trusted server environment. While it is possible to delete a collection from a mobile/web client, doing so has negative security and performance implications.

The snippets below are somewhat simplified and do not deal with error handling, security, deleting subcollections, or maximizing performance. To learn more about one recommended approach to deleting collections in production, see Deleting Collections and Subcollections.

Web
// Deleting collections from a Web client is not recommended.
Swift
// Deleting collections from an Apple client is not recommended.
Objective-C
// Deleting collections from an Apple client is not recommended.

Kotlin+KTX

// Deleting collections from an Android client is not recommended.

Java

// Deleting collections from an Android client is not recommended.

Dart

Deleting collections from the client is not recommended.

Источник

Оцените статью