Home > Mobile >  Error on child(localKey).setValue(item) to update firebase
Error on child(localKey).setValue(item) to update firebase

Time:04-29

I set :

private Query requests;

For a query on Firebase:

requests = db.getReference("Requests")
                .orderByChild("status")
                .endAt("1");

And on update to set a value give me a error on:

requests.child(localKey).setValue(item);

because before I had just

DatabaseReference requests;

and

requests=db.getReference("Requests");

How do I change that? Any help is welcome.

Error on Build:

requests.child(localKey).setValue(item);
                            ^
  symbol:   method child(String)
  location: variable requests of type Query

CodePudding user response:

The following object:

requests = db.getReference("Requests")
                .orderByChild("status")
                .endAt("1");

Is an object of type Query. As you can see, inside the class there is no setValue() method. So that's the reason why you cannot perform such an operation. On the other hand, DatabaseReference class does contain a setValue() method. If you want, however, to use setValue() on the objects that are returned by a query, then you should attach a listener as in the following lines of code:

requests.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                ds.getRef().setValue(item);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

Please note that setValue():

Set the data at this location to the given value.

That being said, I think that you'll be more interested in using the updateChildren(Map<String, Object> update) method, which:

Update the specific child keys to the specified values.

This means that will not override the data at the existing location.

CodePudding user response:

@Alex Mamo so why get() give me a error? On: requests.get().addOnCompleteListener if requests its a type of Query for firebase? Error: requests.get().addOnCompleteListener(new OnCompleteListener() { symbol: method get() location: variable requests of type Query

  • Related