This is the code which is for deleting a perticular post...
Here what i am doing is that when user click the delete button then the post should be deleted but insteed of that nothing is being deleting.Also when i put log to check whether i am getting the unique id generated by firebase database then it shows like this
'2020-04-16 10:00:41.328 29431-29431/com.example.zone D/sanyam: MBlog'
My firebase database Looks Like this(I want to delete the that unique id)
MBlog
-M4iN100Ic5TiSjRRTtX
-M4iNkUGOCd7aKSqg09q
-M4mco3s-nEo0ohXYwIm
-M4xzHyoJjE0QY-5cKeZ
```
//delete button
``` holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPostDatabase = FirebaseDatabase.getInstance().getReference().child("MBlog"); //child name must be same otherwise the
//DatabaseReference newPost = mPostDatabase.getRef();
mPostDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String uid = mPostDatabase.getKey();
Log.d("sanyam",uid);
mPostDatabase.child(uid).removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}```
The dataSnapshot is still a list. To access the item, you need to loop over the result:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String uid = snapshot.getKey();
Log.d("sanyam",uid);
mPostDatabase.child(uid).removeValue();
}
}
But if you run this query all items will remove.
If you want to remove one item you can do it like this:
mPostDatabase = FirebaseDatabase.getInstance().getReference().child("MBlog").child(uid);
mPostDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String uid = dataSnapshot.getKey();
Log.d("sanyam",uid);
mPostDatabase.removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
If you want to remove all that value at once
mPostDatabase = FirebaseDatabase.getInstance().getReference().child("MBlog");
mPostDatabase.removeValue();
but if you want to delete particular node/ref
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPostDatabase = FirebaseDatabase.getInstance().getReference().child("MBlog"); //child name must be same otherwise the
//DatabaseReference newPost = mPostDatabase.getRef();
mPostDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String uid = dataSnapshot.getKey();
Log.d("sanyam",uid);
if(uid.equal("M4mco3s-nEo0ohXYwIm")){//Here you can check UID
removeDataRef(dataSnapshot.getRef())
}
}
//mPostDatabase.child(uid).removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
And If you want to get callback of remove complete here is the listener
public void removeDataRef(DatabaseReference ref){
ref.removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
//Here you can check the operation of remove completed or not
}
});
}
Related
I am trying to create an application where I need to get the availability of a WC from the firebase database,
The problem however is that the android studio only checks the last added item, and brings me its status,
This is my code
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Bathrooms");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
for ( DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Bathrooms bathrooms = dataSnapshot1.getValue(Bathrooms.class);
bathroomsArrayList.add(bathrooms);
}
Browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(bathrooms.getAvailability().equals("Yes")&&bathrooms.getFloor().equals(Floor.getSelectedItem())&&bathrooms.getSection().equals(Section.getSelectedItem())){
disable.setChecked(true);
Toast.makeText(getActivity(), "Browse done successfully", Toast.LENGTH_SHORT).show();
}
else {
disable.setChecked(false);
Toast.makeText(getActivity(), "No bathrooms", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(), "Opsss.... Something is wrong", Toast.LENGTH_SHORT).show();
}
});
return rootview;
}
And this is a picture of the firebase where the data is in
I am not using an arrayadapter, because I want the data to be updated constantly since I will be using a sensor.
this work for you
replace users white name Database Head
myRef = FirebaseDatabase.getInstance().getReference().child("users");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Log.d("rrr", "onDataChange0: ");
for (DataSnapshot dataSnapshot:snapshot.getChildren())
Log.d("rrr", "onDataChange: "+dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
when I'm trying to run this code it fails because it tries to cast HashMap to List view, which probably means the class of the value is HashMap.
final DatabaseReference dayRef = FirebaseDatabase.getInstance().getReference().child("days").child(day.getYear())
.child(day.getMonth()).child(day.getDayOfMonth());
//Reference initialize for writing
final DatabaseReference morningsRef = dayRef.child("need morning");
morningsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (student.needMorning){
ArrayList<Student> morningStudents = (ArrayList<Student>) dataSnapshot.getValue();
morningsRef.setValue(morningStudents);
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("TAG", databaseError.getDetails());
}
});
but then i tried to run this code:
morningsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (student.needMorning){
ArrayList<Student> morningStudents = (ArrayList<Student>) dataSnapshot.getValue();
morningsRef.setValue(morningStudents);
Toast.makeText(context,morningStudents.getClass().toString(),Toast.LENGTH_LONG)
.show();
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("TAG", databaseError.getDetails());
}
});
The toast said:
class java.util.ArrayList
this is a sample of my JSON:
What is wrong here?
For my chat application, I have saved EditText data to firebase but not I am not able to display the same in ListView. I am able to see the EditText data in Firebase database and I want to retrieve it in a ListView. Anybody can help me?
public class Chatbox extends AppCompatActivity {
private DatabaseReference databaseReference;
private Button btnsend;
private EditText editText;
private ListView listView;
private ArrayList<String> arrayList = new ArrayList<>();
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbox);
databaseReference = FirebaseDatabase.getInstance().getReference();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
btnsend = findViewById(R.id.sendbutton);
editText = findViewById(R.id.typemessage);
listView = findViewById(R.id.listmessages);
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.child("Chat").child("Name").push().setValue(editText.getText().toString());
}
});
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getKey();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
catch (Exception ex)
{
Toast.makeText(Chatbox.this, "Error " + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try this
FirebaseDatabase.getInstance()
.getReference("Chat")
.child("Name")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<String> chatMessages = new ArrayList<>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
try {
String chatMessage = String.valueOf(dataSnapshot.child(dataSnapshot1.getKey()).getValue());
chatMessages.add(chatMessage);
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
callback.onFailure(null);
}
});
i guess you want to retrive data not the key:
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getValue();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
or want you to store both in a array list key and value together?
You're adding the messages to the database with:
databaseReference.child("Chat").child("Name")
That means you must also read the messages from the same path:
databaseReference.child("Chat").child("Name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.getValue(String.class);
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()l
}
});
The changes:
Listen to the same node as you're adding the messages to.
Removed the nested listener, which is not needed.
Get the value from each child snapshot, instead of trying to read a non-existing Name property.
Removed the try...catch as the default behavior is to write messages to logcat, which is more useful than showing them in a toast.
Implemented onCancelled, because you should never ignore errors.
I have a node named "Chats" under this node there are many chats with a specific ID. Each these Nodes with the ID contain messages. The messages should be added without any specific path. How can I do that?x
I have this following code, but I'm missing one level:
final DatabaseReference chat = FirebaseDatabase.getInstance().getReference("CHATS").child(chatID);
chat.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
chat.child("_s").setValue(sender);
chat.child("_r").setValue(reciever);
chat.child("_m").setValue(msg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I need the values to be created in one node as a message. But they are created directly under the chatID. Something like this:
final DatabaseReference chat = FirebaseDatabase.getInstance().getReference("CHATS").child(chatID);
chat.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
chat.CHILD().child("_s").setValue(sender);
chat.CHILD().child("_r").setValue(reciever);
chat.CHILD().child("_m").setValue(msg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The structure should look like this:
https://cdn-images-1.medium.com/max/800/1*AHL1ZE8Kt1ctIL2LfZ0z1w.png
It worked with a combination of ValueEventListener and push().setValu(Object):
final String chatID = getChatLeaderID(sender, reciever);
final DatabaseReference chat = FirebaseDatabase.getInstance().getReference("CHATS2").child(chatID);
final HashMap<String, Object> hashMapMsg = new HashMap<>();
hashMapMsg.put("_s", sender);
hashMapMsg.put("_r", reciever);
hashMapMsg.put("_m", msg);
chat.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chat.push().setValue(hashMapMsg);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I have been making a project using firebase for a delivery system app.
Problem: In this image, I need to get these two keys(or parent I think) and store them in a string or if possible I just want to know if I can check if the Id in user has a duplicate. How to check if these key has duplicate or exist and store it on a string if it does exist.
Updated code,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manageordergrocery);
mRecyclerView2= findViewById(R.id.recyclerview1);
mRecyclerView2.setHasFixedSize(true);
mRecyclerView2.setLayoutManager(new LinearLayoutManager(this));
mModel2 = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
mAdapter2=new ViewHolder1(Manageordergrocery.this, mModel2);
mRecyclerView2.setAdapter(mAdapter2);
mDatabaseReference2= FirebaseDatabase.getInstance().getReference("Users");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
String myParentNode = postSnapshot.getKey();
mDatabaseReference2 = FirebaseDatabase.getInstance().getReference();
mDatabaseReference2.orderByKey().equalTo(myParentNode).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String saveNode = dataSnapshot.getKey();
mDatabaseReference2 = FirebaseDatabase.getInstance().getReference(saveNode).child("Ordered");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren()) {
Model1 model2 = postSnapshot.getValue(Model1.class);
mModel2.add(model2);
}
mAdapter2.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Manageordergrocery.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Can someone help me, please? I'm still new in firebase and don't know how to do it.
To obtain the two keys you can do the following:
mDatabaseReference2 = FirebaseDatabase.getInstance().getReference("User");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
String myParentNode = postSnapshot.getKey();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.orderByKey().equalTo(myParentNode).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot posts :dataSnapshot.getChildren())
{
String key = posts.getKey();
if(key.equals(myParentNode))
Toast.makeText(Manageordergrocery.this,"equals", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Manageordergrocery.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
Here first you add a reference to node User then you loop inside that node and retrieve the key using getKey(). After that you attach another listener to the root location and using orderByKey().equalTo(myParentNode) you can check if you have two keys with the same value and do the required.