Unable to Perform Update Operation a Nested Item in Firebase Database? - android

Hello Everyone, I am trying to perform a Update Operation in a Nested Firebase Database .
This is the structure of the database:
I am trying to Update the title text which has Deviled Eggs to Deviled Eggs Updated . I am showing the Data in a RecyclerView
The Only thing I have right Now is the name Appetizers and Snacks .
So basically , First I have to Locate the name Appetizers and Snacks , then Move to the Top Node (0 in this case). Then come down to recipes Node , then get the Current Adapter Key and finally Update the Data
here is the Adapter code that i have tried till now:
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String, Object> map = new HashMap<>();
map.put("title", title.getText().toString());
map.put("time", timeReqd.getText().toString());
map.put("servings", servings.getText().toString());
map.put("ingredients", ingredients.getText().toString());
map.put("steps", steps.getText().toString());
map.put("image", image.getText().toString());
String received_data = holder.title.getText().toString();
//received data has value Appetizers and Snacks
FirebaseDatabase.getInstance().getReference()
.child("All Categories")
.child(received_data)
.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
dialog.dismiss();
} else {
Toast.makeText(context, "Failed to Update !", Toast.LENGTH_SHORT).show();
}
}
});
I also wrote this Query :
Query query = FirebaseDatabase.getInstance().getReference("All Categories").orderByChild("name").equalTo(received_data);
I know the basics of Update operation but really cant figure out, what should i write here. Please provide Guidance. Thanks

Related

how to update recyclerview when delete an item from adapter class

everyone, I am working with recycler view in android and I'm getting data from firebase. The problem is when I press the delete button data is deleted from firebase but in the application new list is added with the old list but I want to show only the new list which does not change the position of the recycler view only remove that item. I'm doing this all in the adapter class.
final DatabaseReference referencePost = database.getReference().child("Posts").child(holder.postId);
referencePost.setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (!task.isSuccessful()) {
Toast.makeText(holder.itemView.getContext(), "" + Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
});
After making sure that the deletion process from Firebase is complete, you can add this line:
.
.
//Successfully Deleted
notifyDataSetChanged ();
You can read about it more than this.

Multiply reading of document references from Firestore using tasks

I have a Map of references which I read from Firestore. these refs lead me to documents that I'm willing to use their data to create an instance of my class 'Contact'.
In order to do that I've created a list of tasks which every task of it uses its ref to read from Firestore and retrieve the needed data.
Once it's all done I use Tasks.whenAll(tasks).addOnSuccessListener() willing to retrive my new array of Contacts.
On this method, 'contacts' is empty and 'data' is full of document references.
I expected Tasks.whenAll(tasks) to being called only when all this reading using the refs has completed, however it's being called immediately, therefore - nothing happens.
private void createContactArray(final ArrayList<Contact> contacts, final Map<String, DocumentReference> data) {
List<Task<DocumentSnapshot>> tasks = new ArrayList<>();
for (final Map.Entry<String, DocumentReference> entry : data.entrySet()) {
tasks.add(db.document(entry.getValue().getPath()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String,String> contactDetails = (Map<String, String>) document.getData().get(entry.getKey());
Contact contact = createContact(contactDetails);
if(contact != null){ contacts.add(contact);}
} else {
Log.d(ACTION_FETCH_CONTACT_LIST,"There was ref problem with " + entry.getKey());
}
}else {
Log.d(ACTION_FETCH_CONTACT_LIST, "get failed with ", task.getException());
}
}
}));
}
Tasks.whenAll(tasks).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
sendBroadcastActionContactList(contacts);
}
});
I would like Tasks.whenAll to be called once its all finished and not right away. I wish to have a proper explanation for the issue and a decent code that should do the job instead of mine.
I really appreciate your help!
You are using the APIs incorrectly. You should be collecting tasks returned by get() into an array, instead of immediately adding a callback to each one. Pass that list of tasks to Tasks.whenAll(). Then, in the callback for the task returned by Tasks.whenAll, you can examine each DocumentSnapshot results.

How can I find existing node by name and append some extra values to the existing ArrayList in Firebase Database?

I am building an app using Firebase where I am checking for presence of certain values in the node and if it is present I am just adding to it instead of creating a new node.
But when I try to implement the same its actually implementing infinite query and database getting filled up
For simplicity I am including that portion of the code that is causing problem:
Here the else coode means as the data node is already present in the database I am appending.
else {
user u=new user(SharedPrefManager.getmInstnce(ChatList.this).getUsername(),SharedPrefManager.getmInstnce(ChatList.this).getmail());
for(int l=0;l<grpar.size();l++){
if(grpar.get(l).getName().equalsIgnoreCase(grpname)){
index=l;
break;
}
}
Log.i("Checking QUERY","Value exist!!!! in "+ index);
grpar.get(index).getGrpMembers().add(u);
Group grp=new Group(grpname,grpar.get(index).getGrpMembers());
grpRef.push().setValue(grp).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Intent intent = new Intent(ChatList.this,MainActivity.class);
intent.putExtra("Id","none");
intent.putExtra("Name",grpname);
startActivity(intent);
}
else
{
Toast.makeText(ChatList.this,"Data Not Added Completely",Toast.LENGTH_SHORT).show();
}
}
});
}
From the moment I applied the following logic it started behaving abnormally:
for(int l=0;l<grpar.size();l++){
if(grpar.get(l).getName().equalsIgnoreCase(grpname)){
index=l;
break;
}
}
I am also attaching the DB structure:
I cannot figure out where the error is ! Any help is appreciated

Firebase not creating new node

I have one node name users which is populating fine, but I am trying to incorporate a new node events, which I am having trouble with. I have copied exactly what works in the users, but I am clearly doing something wrong. It never goes into the OnCompleteListener. Is there something I am missing?
R.string.dbnode_events ="events"
Events events = new Events();
events.setEvent_key(mEventKey);
events.setEvent_title("");
events.setEvent_date("");
events.setEvent_time("");
events.setEvent_millis("");
events.setEvent_desc("");
events.setEvent_filter("");
events.setGroup_number("");
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbnode_events))
.child(mEventKey)
.setValue(events).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(CreateEventActivity.this, "Success", Toast.LENGTH_SHORT);
}
});
More Information/ Example: The top user one creates a node no problem but the events one has yet to create. I hope this might give some more insight.
User user = new User();
user.setName(email.substring(0, email.indexOf("#")));
user.setPhone("1");
user.setProfile_image("");
user.setSecurity_level("1");
user.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
user.setEmail(FirebaseAuth.getInstance().getCurrentUser().getEmail());
user.setStreet_address("");
user.setCity("");
user.setState("");
user.setZip("");
user.setMember_filter("Member");
user.setSmall_group_subscription1("");
user.setSmall_group_subscription2("");
user.setSmall_group_subscription3("");
user.setSmall_group_subscription4("");
user.setSmall_group_subscription5("");
user.setShow_phone("No");
user.setShow_email("Yes");
user.setShow_address("No");
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbnode_users))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
.addOnCompleteListener(task1 -> {
FirebaseAuth.getInstance().signOut();
redirectLoginScreen();
}).addOnFailureListener(e -> {
FirebaseAuth.getInstance().signOut();
redirectLoginScreen();
Toast.makeText(RegisterActivity.this, "Database Problem ",Toast.LENGTH_SHORT);
});
/////////////////////////
String mEventKey = UUID.randomUUID().toString();
Events events = new Events();
events.setEvent_key(mEventKey);
events.setEvent_title("");
events.setEvent_date("");
events.setEvent_time("");
events.setEvent_millis("");
events.setEvent_desc("");
events.setEvent_filter("");
events.setGroup_number("");
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbnode_events))
.child(mEventKey)
.setValue(events)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(RegisterActivity.this, "Success", Toast.LENGTH_SHORT);
}
});
This is what i have done, probably it will help :D
When you add a class, you have to create a reference like this :
private DatabaseReference Accounts;
And inside the onCreate :
Accounts = FirebaseDatabase.getInstance().getReference("Accounts");
After that, set ur class. I do this for the user :
currentwithID = new Class_user(uID,uSer,matchFound);
And than set it on the node :
uID is the token given by Google
Accounts.child(uID).setValue(currentwithID);
I have done the same things to every node of my database, and it perfectly works.
Try to do that with this code, and tell me if it works :D

how to delete firebase position value using swipe controller

how to delete firebase values using position (swipe controller)
if i delete values using below method,its delete random values,,i want delete selected value only
swipeController = new SwipeController(new SwipeControllerActions() {
#Override
public void onRightClicked(int position) {
firebaseRecyclerAdapter1.notifyItemRemoved(position);
firebaseRecyclerAdapter1.notifyDataSetChanged();
mDataRef = FirebaseDatabase.getInstance().getReference().child("OrderItemsList").child(gg);
mDataRef.child(d).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FancyToast.makeText(getApplicationContext(), "Removed Item", FancyToast.LENGTH_LONG, FancyToast.ERROR, R.drawable.ic_clear_black_24dp).show();
firebaseRecyclerAdapter1.notifyDataSetChanged();
firebaseRecyclerAdapter1.startListening();
}
}
});
It looks like you're using an adapter from FirebaseUI. In that case, you can get the DatabaseReference for the node at position with:
mDataRef = firebaseRecyclerAdapter1.getRef(position);
And then you can delete the data at that reference with:
mDataRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
...
You need to specifiy which item you're trying to delete. For example, in your case, it should be:
mDataRef = FirebaseDatabase.getInstance().getReference().child("OrderItemsList");
mDataRef.child("Egg Rice").removeValue().addOnCompleteListener.. // and the rest..
Here is how it should be without code: OrderItemsList -> Egg Rice child.

Categories

Resources