Unable to update value in Firebase database from Android app - android

With the following code, I have the "history node".
History Node
{
"History" : {
"-LJANnl9ofbXlxLGxTGg" : {
"destination" : "3 Paradise Row",
"driver" : "ReGqRl2IIUhmLIqdBqBIELHBsgE3",
"location" : "1 Union St",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 5.25,
"rider" : "l3PPyBQux7YJhGGTdexxwDBteLM2",
"riderPaid" : "true",
"status" : "accepted",
"timestamp" : 1533494377
}
}
With the following code, I am trying to update "status" value to update from "accepted" to "arrived_loc". When I run the code, I have a yellow highlight in firebase but keeps the value of status "accepted".
update status to "arrived_loc"
driverId = FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRefchild("History").orderByChild("driver").equalTo(driverId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot nodeDS = dataSnapshot.getChildren().iterator().next();
String key = nodeDS.getKey();
Log.e(TAG, "key = " + key);
String path = "/" + dataSnapshot.getKey() + "/" + key;
Log.e(TAG, "path = " + path);
HashMap<String, Object> update = new HashMap<>();
update.put("status", "arrived_loc");
rootRef.child(path).updateChildren(update);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
What am I doing wrong?
Edit #1
If I run this code:
DatabaseReference arrivedLoc = FirebaseDatabase.getInstance().getReference("History");
String historyId = arrivedLoc.push().getKey();
arrivedLoc.child(historyId).child("status").setValue("arrived at pickup");
I get an extra history node and no update:
"History" : {
"-LJAVN2iAWfRREdlBevb" : {
"destination" : "3 Union St",
"driver" : "ReGqRl2IIUhmLIqdBqBIELHBsgE3",
"location" : "123 Main Street",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 5.38,
"rider" : "l3PPyBQux7YJhGGTdexxwDBteLM2",
"riderPaid" : "true",
"status" : "accepted",
"timestamp" : 1533496391
},
"-LJAVaFd3Gzq3iIZGHeP" : {
"payment response" : "approved",
"riderPaid" : "true",
"status" : "accepted"
}
}
Edit #2 - image of database frozen
Edit #3
I can't seem to get it working for some reason so I renamed "status" to be "requestStatus" and created a new variable called rideStatus like:
status = "arrived at pickup";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History");
rootRef.child(requestId).child("rideStatus").setValue(status);
This seems to work for now, but when I need to change the value of rideStatus, hopefully it will work.

Try with this code without push() function:
DatabaseReference arrivedLoc = FirebaseDatabase.getInstance().getReference("History");
String historyId = arrivedLoc.getKey();
arrivedLoc.child(historyId).child("status").setValue("arrived at pickup");
(depends on what you need to achieve on your app, might be a little different)
Update #2:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History");
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
snapshot.getRef().child("status").setValue("arrived at pickup");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Try with updateChildren():
driverId = FirebaseAuth.getInstance().getCurrentUser().getUid();
HashMap<String, String> newData = new HashMap<>();
newData.put("status", "arrived_loc");
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History/" + driverId); // Or however the path is
rootRef.updateChildren(newData);

Related

Android Firebase Retrieving data as a list from multiple nods

I am using firebase realtime database in my first android app. I'm trying to retrieve data from firebase as an arraylist of "username" but i'm constantly having the Query returning a null result. i'm very new to firebase so i'm really struggling with data retrieval errors.
"Marchand" : {
"Taha" : {
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"
},
"Yasmine" : {
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"
}
.
.
.
This is one of my attempts, i tried to use the order-by-child method to iterate through the multiple nods that i have but i'm sure that it's not the right way to do this, this gives me null poiter exceptions because the datasnapshot is returning a NULL value :
referenceMarchand = rootNode.getReference("Marchand");
final ArrayList<String> types = new ArrayList<>();
Query users = referenceMarchand.orderByChild("username");
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
types.add(dataSnapshot.child("username").toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
lets make use of some functions of firebase, Lets see it works for you.
part 1)
we will save it another way around
"Merchant" : {"Name" : "Taha"
"ID" :"-KSMCMCMnnkd"},//Firebase generated id
{"Name" : "Yasmine"
"ID" :"-KSMCMccccnkd"},//Firebase generated Id
...........
Part 2)
And Save the Details
"Details" : {
"ID" : "-KSMCMCMnnkd" //Firebase generated id
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"},
{
"ID":"-KSMCMccccnkd" //Firebase generated id
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"}
In Part 1)
DatabaseRefrence ref = FirebaseDatabase.getInstance("/Path");
String id = ref.child("Merchant").push().getKey(); //Firebase generated id
Merchant merchant = new Merchant();
merchant.setId(id);
merchant.setName("SomeName");
ref.child("Merchant").child(id).setValue(merchant);
Part 2)
Detail detail = new Detail();
detail.setAddress("Some Address");
detail.setBlockage("false");
detail.setLatitude("SomeValue");
detail.setEmail("someText#gmail.com");
......
ref.child("Details").child(id).setValue(detail);
Now
List<Merchant> merchants = new ArrayList<>();
List<Detail> details = new ArrayList<>();
ref.child("Merchant").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Merchant merchant = snapshot.getValue(Merchant.class);
merchants.add(merchant);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ref.child("Details").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Detail detail = snapshot.getValue(Detail.class);
details.add(detail);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Now you can get the details for some merchant or save it in local database for later querying.

Firebase Listener Skip

I have converted to Firebase for my Android development as I want to utilise the many features of Firebase (Notifications, Messaging, Storage etc), however, I am having difficulty receiving data from Firebase and cannot find detailed information online. Yes, I have tried the documentation but it does not explain the events I am experiencing.
I want to retrieve all the data that I have an insert it into an arraylist of objects. Here is a static example:
users[i] = new User("James" + (i*2.5), "Hmack00" + (i*2), "https://firebasPic_2019.03.03.05.26.35.jpg.jpg?alt=media&token=cf", "United Kingdom");
Database:
{
"Users" : {
"4PdlTlv3qjZ3BmDvrJyUut9Fnq43" : {
"Country" : "xx",
"Fullname" : "hh",
"ProfilePicture" : "htm/o/Images%2FSearchAdapter%2F4PdlTlv3qjZ3BmDvrJyUut9Fnq43%2FProfilePicture%2FProfilePic_2019.03.06.10.47.54.jpg.jpg?alt=media&token=b647708e-c6d5-4b45-bef0-3dc40301b73a",
"Username" : "hmack001"
},
"COg4r4io9hezhFpmK3adPucUXA93" : {
"Country" : "spain",
"Fullname" : "nat",
"ProfilePicture" : "hcom/o/Images%2FSearchAdapter%2FCOg4r4io9hezhFpmK3adPucUXA93%2FProfilePicture%2FProfilePic_2019.03.06.19.14.17.jpg.jpg?alt=media&token=8620b321-5cef-42f0-a828-dbb7c37c8e7d",
"Username" : "nat"
},
"Tw1xRxViygNsLqrQiaaMAvAduIu1" : {
"Country" : "uk",
"Fullname" : "harvey\n",
"ProfilePicture" : "t.com/o/Images%2FUsers%2FTw1xRxViygNsLqrQiaaMAvAduIu1%2FProfilePicture%2FProfilePic_2019.03.03.05.26.35.jpg.jpg?alt=media&token=c290e75a-5f92-4271-bcb5-c644fe1b14ef",
"Username" : "RGB"
},
"vOxr1RoDqgWogKK1lp9pfpTHc6w2" : {
"Country" : "scotland ",
"Fullname" : "greg greg",
"ProfilePicture" : "ot.com/o/Images%2FSearchAdapter%2FvOxr1RoDqgWogKK1lp9pfpTHc6w2%2FProfilePicture%2FProfilePic_2019.03.04.12.30.22.jpg.jpg?alt=media&token=27b024cf-0691-4121-8a27-26acf101ebc2",
"Username" : "greg"
},
"xecUOPeyMcQaQrgkU9ouDgK90Ai1" : {
"Country" : "ggh",
"Fullname" : "Da apply ",
"ProfilePicture" : "2FProfilePic_2019.03.03.04.58.50.jpg.jpg?alt=media&token=f35854c2-3ff9-4d18-9f7a-10c13f066c68",
"Username" : "gg"
}
}
}
Here is my code and I will explain my errors after (I have left in 'zombie' code, to show the attempts that I have made)
//Firebase Variables
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
//Firebase Data
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
userId = mAuth.getCurrentUser().getUid();
myRef = mFirebaseDatabase.getReference().child("Users").child(userId);
//Firebase Data
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) { //Function called every time a change is made to the database
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { //Function called when there is an error in the database/ with the call
Log.d("Print","Cancelled Firebase: " + databaseError.toString());
}
});
}
private void showData(DataSnapshot dataSnapshot) {
int userCount = 5;
int i = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//User user = new User();
//User user = new User(); //Get Count of Firebase Users
//user = new User();
if (ds.child(userId).exists()) {
/*user.setFullname(ds.child(userId).getValue(User.class).getFullname()); //set the full name
user.setUsername(ds.child(userId).getValue(User.class).getUsername()); //set the username
user.setProfilePicture(ds.child(userId).getValue(User.class).getProfilePicture()); //set the profile picture
//Display Information
Log.d("DataSnapchat Test", "ShowData Name: " + user.getFullname());
Log.d("DataSnapchat Test", "ShowData Username: " + user.getUsername());
Log.d("DataSnapchat Test", "ShowData Picture: " + user.getProfilePicture());
ArrayList<String> userArrayList = new ArrayList<>();
userArrayList.add(user.getFullname());
userArrayList.add(user.getUsername());
userArrayList.add(user.getProfilePicture());
*/
String fullname = (String) ds.child(userId).child("Fullname").getValue();
Toast.makeText(this, "Fullname: " + fullname, Toast.LENGTH_SHORT).show();
//UserListAdapter adapter = new UserListAdapter(this, R.layout.find_profiles_search, userArrayList, mProfileSearch);
//mListView.setAdapter(adapter);
i++;
}
}
}
When I debug the code the showData function is never called and neither functions within the Value Event Listener are called, is this an Async Problem?
Currently I am trying to fetch data and insert it into a variable (Literally any data, once I have a working query I can convert it to fit by manipulating child fields etc).
Question: Does the addValueListener only work when data is changed in the database? If so then what is the alternative, if not then why are the functions not operating.
I do not recieve any errors and nothing is logged to the console.
I want to put my database into an array list, I know that I shouldnt use getChildren to do this, put I am trying to test if I can get any data before I try and get all the data.
You have some really weird loops in showData(). Since you're attaching a ValueEventListener to the node of the specific user, you can just look up the property values for that specific user:
myRef = mFirebaseDatabase.getReference().child("Users").child(userId);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("OnDataChange", dataSnapshot.getKey());
Log.d("OnDataChange", dataSnapshot.child("Fullname").getValue(String.class));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("Print","Cancelled Firebase: " + databaseError.toString());
}
});

Getting name of child node which is holding another subchild

Child1
Child1.1
Subchild1
Subchild 2
Child 1.2
Subchild 1
Subchild 2
If I need to retrieve child1.1 and 1.2 how do I get them in textview?, as their subchild can be retrieved easily using datasnapshot.
I dont have enogh reputation to post image so have to type the structure of my firebase project. Hope my problem is understandable.
Code What i done is...
LoggedInRef.child(number).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null) {
if (sampleList != null) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
/* msg_List_Item msgLIST=ds.getValue(msg_List_Item.class);
msgList.add(msgLIST);*/
Log.d("MESSAGES<<<<<<<<", ds.getValue().toString() + "<<<<<<<<<<<<<<<<<<<<<<<<<<");
String msg = ds.getValue(String.class); // problem is here............................................
String time = ds.child("DateTime").getValue(String.class);
String tag = ds.child("Tag").getValue(String.class);
msg_List_Item msg_list_item = new msg_List_Item(msg, time, tag);
/* msg_list_item.setMsg(msg);
msg_list_item.setDateTime(time);
msg_list_item.setTag(tag);*/
msgList.add(msg_list_item);
MessageAdapter = new msgAdapter(msgList, getApplicationContext());
mRecyclerView.setAdapter(MessageAdapter);
sampleList.clear();
mRecyclerView.scrollToPosition(MessageAdapter.getItemCount());
}
}
}
else {
Toast.makeText(Message.this, "No data found", Toast.LENGTH_SHORT).show();
}}
#Override
public void onCancelled(DatabaseError databaseError) {
}}
);
"1234567890" : {
"-L7AhB1GWZPNqlte0tiX" : {
"DateTime" : "09-03-2018 22:30",
"MSG" : "hiii ",
"Tag" : "ByMe"
},
"-L7AiOxVbSYAx8_0WqEa" : {
"DateTime" : "09-03-2018 22:35",
"MSG" : "how are you",
"Tag" : "ByMe"
},
"-L7Ak1lhqn9EfD5YCOou" : {
"DateTime" : "09-03-2018 22:42",
"MSG" : "what are u doing?",
"Tag" : "ByMe"
},
"-L7AkGekOzKzlLOwWNWp" : {
"DateTime" : "09-03-2018 22:43",
"MSG" : "I am fine",
"Tag" : "NotByMe"
here is my Re modified structure!!!. *Child node : * "DateTime", "MSG", "Tag" become easier to fetch by using push().

Getting Logged in User details from Firebase real time databse

I am using Firebase real-time database and registered user details with Email and Password authentication.
Now, I can successfully do login and logout for registered users.
Now, I have to get details of currently logged in user.
My database structure is as below :
{
"UserInfo : " : {
"User ID : CxQNTJwnoleIk9M1iYMT9TsrJst2" : {
"-Kvb_W0YWX7M8dPF7Kn9" : {
"contact" : "8888888888",
"email" : "visu#gmail.com",
"firstname" : "Vish",
"lastname" : "Mo",
"password" : "vish",
"strUserId" : "CxQNTJwnoleIk9M1iYMT9TsrJst2"
}
},
"User ID : e1VCGeshWfOeptzzj4kP1POtmhk2" : {
"-KvbTM1Jtzn3r9V7II47" : {
"contact" : "9999999999",
"email" : "ja#gmail.com",
"firstname" : "Ja",
"lastname" : "Mo",
"password" : "ja123#",
"strUserId" : "e1VCGeshWfOeptzzj4kP1POtmhk2"
}
}
}
}
For example, If I have logged in with email: visu#gmail.com then I want to get all the details of that user.
How can I do it ??
Ya, I can get Email and Displayname as below :
FirebaseUser user = firebaseAuth.getCurrentUser();
txtUsername.setText("Welcome, " + user.getDisplayName() + "\n" + user.getEmail());
But, I want to get all the details of that user from above-specified database structure. Please, guide me. Thanks.
When you do as this:
FirebaseUser user = firebaseAuth.getCurrentUser();
txtUsername.setText("Welcome, " + user.getDisplayName() + "\n" + user.getEmail());
It's just your Authentication field, not your database.
As first, you should define these field by:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
In your db structure:
mDatabase.child("UserInfo : ").child("User ID : CxQNTJwnoleIk9M1iYMT9TsrJst2").child("-Kvb_W0YWX7M8dPF7Kn9").child("contact").getValue();
In the end, refactor your db structure by simple word. UserID, Email, Password is redundant because which can be taken by Authentication Field.
Read more: https://firebase.google.com/docs/database/android/read-and-write
try this. hope this will work
FirebaseUser user = firebaseAuth.getCurrentUser();
FirebaseDatabase.getInstance().getReference().child("UserInfo")
.child(user.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
UserClass curUser = dataSnapshot.getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
And Finally, I have done as below :
private void showData() {
progressDialog=new ProgressDialog(ProfileActivity.this);
progressDialog.setMessage("Getting data...");
progressDialog.show();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference().child("UserInfo : ").child("User ID : " + firebaseAuth.getCurrentUser().getUid());
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
progressDialog.dismiss();
User user = dataSnapshot.getValue(User.class);
txtFname.setText(user.getFirstname());
txtLname.setText(user.getLastname());
txtEmail.setText(user.getEmail());
txtPassword.setText(user.getPassword());
txtContact.setText(user.getContact());
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this, "Couldn't get data.", Toast.LENGTH_SHORT).show();
}
};
mDatabase.addValueEventListener(postListener);
}
Created a method, in which loaded ProgressDialog first, then took a Database refrence and initialized it up to my databse node with getting UUid from FirebaseAuth instance. Attached ValueEventListener and inside method : onDataChange, used instance of DataSnapshot to get value for my User class. and Finally displayed fetched data to my textviews.
Thanks all for your efforts. upvoted.
EDIT :
My new structure is as below :
{
"UserInfo : " : {
"User ID : I6wWODplkNXqAhSCRZsH6sjf4mM2" : {
"contact" : "9999999990",
"email" : "dhaval#gmail.com",
"firstname" : "Dhaval",
"lastname" : "Patel",
"password" : "dhaval123",
"strUserId" : "I6wWODplkNXqAhSCRZsH6sjf4mM2"
},
"User ID : Nf4kDsxAXYbclt16HahkzsYABWE3" : {
"contact" : "9999999999",
"email" : "bandish#gmail.com",
"firstname" : "Bandish",
"lastname" : "Mehta",
"password" : "bandish123",
"strUserId" : "Nf4kDsxAXYbclt16HahkzsYABWE3"
}
}

How to structure my sport manager Firebase database

I'm building a sport manager app that let the users create their own competitions and update the match results to be consults for other participants.
I read a lot about how flat the database (I come from SQL :-) and saw many video tutorials from the Firebase Team.
At this point I have this structure:
{sport-manager :
...
groups : {
"groupId1" : {
competitionId : "competitionId1"
name : "Group A",
type : "LEAGUE"
},
"groupId2" : {
competitionId : "competitionId1"
name : "West playoofs",
type : "PLAYOFFS"
},
...
},
players : {
"playerId1" : {
birthday : 351408600000,
firsName : "Jhon",
lastName : "Doe",
shirtNumber : 0,
teamId : "teamId1"
},
...
},
teams : {
"teamId1" : {
competitionId : "competitionId1"
name : "Team 1",
},
...
},
teamGroupStats : {
"groupId1" : {
"teamId1" : {
goalsAgainst: 0,
goalsFavor: 0,
matchesDraw: 0,
matchesLoss: 0,
matchesPlayed: 0,
matchesWin: 0,
points: 0,
teamName: "Team 1",
},
"teamId2" : {
...
},
...
},
"groupId2" : {
"teamId2" : {
...
},
...
}
...
}
}
This structure let me make queries to populate a ListView adapter with the data of all the teams that are part of a group in this way:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Query groupQuery = mDatabase.child("teamGroupStats").child("groupId1")
Or when I have to get the player from determinated team:
Query playersQuery = mDatabase.child("players").orderByChild("teamId").equalTo("teamId1");
So far, so good. My problem come when I have to delete a team from this structure. For avoid integrity problems I use multipath update to delete all.
A team can have one or more players
A team can be part of one or more groups.
With that in mind, I can delete any teams with all his players.
Map<String, Object> deleteMap = new HashMap<>();
deleteMap.put("teams/teamId1", null);
Query playersQuery = mDatabase.child("players").orderByChild("teamId").equalTo("teamId1");
playersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot playerSnapshot : dataSnapshot.getChildren()){
deleteMap.put("players/" + playerSnapshot.getKey(), null);
}
// Delete all in one call!
mDatabase.updateChildren(deleteMap);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
How I can make a query to get all the paths with "teamId1" has secundary key in the structure "teamGroupStats"?
His this structure good for the use I need?
IMHO your database is very well structured. Regarding your question, you cannot get all paths as you say. What can you do, is to delete data in the same way as you add it. So in order to delete all data i recomand you using this method:
private static void deleteTeam(String teamId) {
Map<String, Object> map = new HashMap<>();
map.put("/teams/" + teamId, null);
map.put("/teamGroupStats/groupId1/" + teamId, null);
map.put("/players/playerId1/teamId/", null);
databaseReference.updateChildren(map);
}
A more generic method will be:
private static void deleteTeam(String reference, String teamId) {
Map<String, Object> map = new HashMap<>();
map.put(reference, null);
databaseReference.updateChildren(map);
}
If you need to query the database to get additional data, use getRef() method to get the reference and pass those values to the second method.
All your data will be deleted at once atomically.
Hope it helps.
Finally I found one solution. I modified my database to store all the groups Id's where the team belong inside the Team structure.
teams : {
"teamId1" : {
competitionId : "competitionId1"
groups : {
"groupId1" : true,
"groupId6" : true,
...
},
name : "Team 1",
},
...
With that information, I can add an inner ValueEventListener in the playersQuery's listener and make the update/delete.
public static void deleteTeam(final String teamId){
Map<String, Object> deleteMap = new HashMap<>();
deleteMap.put("teams/" + teamId, null);
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Query playersQuery = mDatabase.child("players").orderByChild("teamId").equalTo(teamId);
playersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot playerSnapshot : dataSnapshot.getChildren()){
String playerId = playerSnapshot.getKey();
deleteMap.put("players/" + playerId, null);
}
mDatabase.child("teams").child(teamId).child("groups")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot groupSnapshot : dataSnapshot.getChildren()){
String groupId = groupSnapshot.getKey();
deleteMap.put("teamGroupStats/" + groupId + "/" + teamId, null);
}
// Delete all in one call!
mDatabase.updateChildren(deleteMap);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
I wasn't very sure about the inner listener, and I had to made a little change to my database structure, but this works fine.
If anybody knows a better way to do this, I'm open to read it. Thanks!

Categories

Resources