Update Multiple Firebase nodes - android

I need to update few nodes in firebase data which is posted from the server end.Need to update the node "is_done" to 0/1 from the device end.I have tried with different solutions but all became futile i.e it is adding a different node outside the "schedule" node.
Code snippet I have tried
private void updatemultiplefirebasedata() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference reference = firebaseDatabase.getReference();
Query query = reference.child("schedule").child("22-12-2017").child("route").child("1").child("kid").child("21");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
Log.d("Keys",String.valueOf(d.getKey())); //returning all the keys
HashMap<String, Object> result = new HashMap<>();
result.put("is_done", "0");
reference.child(String.valueOf(d.getKey())).updateChildren(result); //update according to keys
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

That's because your database reference still points to the root of your tree. You should assign the desired path to that reference.
Also: You don't need Queries in order to access data directly. You can simply attach a listener to the Database Reference.
private void updatemultiplefirebasedata() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference reference = firebaseDatabase.getReference().child("schedule").child("22-12-2017").child("route").child("1").child("kid").child("21");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
Log.d("Keys",String.valueOf(d.getKey())); //returning all the keys
HashMap<String, Object> result = new HashMap<>();
result.put("is_done", "0");
reference.child(String.valueOf(d.getKey())).updateChildren(result); //update according to keys
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Try this :
reference.child(d.getKey()).updateChildren(result);
remove String.valueOf from child because your key is integer and you are passing it as string so instead of pointing it to same child it will create new key with String "1"

Related

How to get the push id of a specific value in android using firebase

How do I get the push id of the value where child("topic_name").getValue() = "algebre" ?
FirebaseDatabase Structure:
I have already tried push().getKey(); but it returns another key to me.
Try this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(TOP_NODE_NAME).orderByChild("topic_name").equalTo("algebre");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String key = child.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now key has the Key of the node where topic_name=algebra

Firebase query in tree with depth and multiple children

I have a problem regarding querying the firebase database using a value and getting the specific node. My schema is shown here:
In my schema 'workLocations' belongs to an 'excavationWorks', and 'excavationWorks' belongs to an 'excavationLists'.
That means that the path to a specific workLocation is excavationLists/excavationWorks/workLocations/(specific workLocation)
The problem that I have is that I want to query the workLocations node by the location value (let's say London) and get the parent node (the red circled key which is the key of the specific workLocation).
I have search and read many posts but I haven't managed to make it work.
My code looks like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("workLocations").orderByChild("location").equalTo("London");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot workLoc : dataSnapshot.getChildren()) {
// do something with the individual "issues"
Log.d(TAG, workLoc.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you
To achieve this, you need to query your database twice like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference workLocationsRef = reference
.child("excavationLists")
.child("excavationWorks")
.child("workLocations");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String key = ds.getKey();
Query query = workLocationsRef.child(key).orderByChild("location").equalTo("London");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String description = snapshot.child("description").getValue(String.class);
Log.d("description", description);
String partentKey = snapshot.getRef().getParent().getKey();
Log.d("partentKey", partentKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
workLocationsRef.addListenerForSingleValueEvent(valueEventListener);

How to get key value under a key?

I want to use the spinner to display the key which under specific username but unfortunately it returns nothing to the spinner. I used an array to store the key value which under the username.
Here's my database structure
Let's said I am rexyou0831 and I just want to retrieve the 2 usernames which under my username but my code return me nothing to the list. un is my current username variables. Please if you got any idea please share it with me thank you.
Hers' my code
db = FirebaseDatabase.getInstance();
cref = db.getReference("chat");
public ArrayList<String> retrieve()
{
final ArrayList<String> Student=new ArrayList<>();
cref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot c:dataSnapshot.getChildren())
{
if(c.getKey().equals(un)){
for(DataSnapshot d: dataSnapshot.getChildren()){
Student.add(d.getKey());
}
}else{
Student.clear();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return Student;
}
To get those usernames under your username, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("chat").child("rexyou0831");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = ds.getKey();
list.add(userName);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
Your out put will be: [gigi1212, mario123]
Note, that onDataChenge() is called asynchronous which means that is called even before you are adding those keys to the list. As a conslusion, you need to declare and use that list, inside onDataChenge(), otherwise is null.

I'm not able to receive data from my firebase database

I'm a rookie regarding firebase and android.
After reading for a while I have raise a question regarding my code:
I'm not able to read information from my firebase database.
here's my code:
#Override
protected void onStart() {
super.onStart();
mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference referenceArtista = mDatabase.child("artists");
final List<Pintura> pinturaList = new ArrayList<Pintura>();
referenceArtista.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot artistaSnapshot: dataSnapshot.getChildren()) {
Artista artista = artistaSnapshot.getValue(Artista.class);
pinturaList.addAll(artista.getPinturaList());
}
RecyclerView recyclerViewPintura = (RecyclerView)findViewById(R.id.recyclerView);
recyclerViewPintura.setHasFixedSize(true);
recyclerViewPintura.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL,false));
AdapterPintura adapterPintura = new AdapterPintura(getBaseContext(),pinturaList);
recyclerViewPintura.setAdapter(adapterPintura);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
My database structure looks something like this:
Database
I've been debugging and I'm seeing that the list at the end of the foreach cycle, returns null. (hence I'm greeted with a NullPointerException and the app crashes)
Thanks in advance :)
You are getting null because List<Pintura> pinturaList = new ArrayList<Pintura>(); is declared outside the onDataChange() method. You need to declare and use it inside that method and outside the for loop, otherwise is null, due the asynchronous behaviour of the method, which is called before you even add those Artista class objects to the list.
To solve this, please use this code:
referenceArtista.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<Pintura> pinturaList = new ArrayList<Pintura>();
for (DataSnapshot artistaSnapshot: dataSnapshot.getChildren()) {
Artista artista = artistaSnapshot.getValue(Artista.class);
pinturaList.addAll(artista.getPinturaList());
}
Log.d("TAG", artista); // Here is not null
RecyclerView recyclerViewPintura = (RecyclerView)findViewById(R.id.recyclerView);
recyclerViewPintura.setHasFixedSize(true);
recyclerViewPintura.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL,false));
AdapterPintura adapterPintura = new AdapterPintura(getBaseContext(),pinturaList);
recyclerViewPintura.setAdapter(adapterPintura);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to use that list outside onDataChange() method, please see my answer from this post.
Can you initailize your recycler vioew in onCreate method and once you get the data from the firebase just update the adapter
pinturaList = new ArrayList<Pintura>();
dataSnapshot.getChildrenCount();
//List<User> list= new ArrayList<User>();
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Artista artista = artistaSnapshot.getValue(Artista.class);
pinturaList .add(user);
}
adapter.update(pinturaList );
Instead of addListenerForSingleValueEvent use ValueEventlistener then use forEach loop because single return single or null value if you have more than one
Try this
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("YOUR TABLE NAME").getRef();
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
Log.v("dataSnapshot.getValue()", "" + dataSnapshot.getValue());
for (DataSnapshot dss : dataSnapshot.getChildren()) {
HashMap<String, String> map = (HashMap<String, String>) dss.getValue();
//get your values
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Unable to get All child data in Firebase Database using a Map?

I am trying to display all child "name" located in my database tree. My Database tree I used the Map to do so:
GenericTypeIndicator<Map<String, Object>> m = new GenericTypeIndicator<Map<String, Object>>() {};
Map<String, Object> map = snapshot.getValue(m);
String username = (String) map.get("name");
displayName.setText(username);// Display the name
I am displaying all the data into a recyclerView. But for some reasons instead of getting all names(Eva, smith, princess), I am only one which is the lastest one created "princess" being displayed 3 times in my recyclerView layout(princess, princess, princess). Anyone has any idea what I am doing wrong?
Assuming that you have a node named users in which you have all those uid's, to get all those name, please use the code below. Is the easiest way to achieve this.
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userId = (String) dataSnapshot.getKey();
DatabaseReference userIdRef = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue();
Log.d("TAG", name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
Hope it helps.

Categories

Resources