I'm trying to add a new child using the DatabaseReference in my Firebase Android app. I'm doing:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference()
mDatabase.child("childToAdd").setValue(1);
I can do this with a regular Firebase Reference as it would add the child to the database if it isn't there.
How could I go about doing this with DatabaseReference?
Edit: Thanks for all the suggestions but I'm having issues with the following code. When it enters the if block it does not push the data onto the database.
https://gist.github.com/rounaksalim95/a5cba332400c6caf8320f15b0cbf06e8
When I try this with the old Firebase reference I get error code 11 (User code called from firebase runloop) and with the new database reference I get error code -3 (PermissionDenied even though I have no security rules).
Update:
I got it to do what I wanted to using a single value event listener:
Firebase userRef = new Firebase(BASEURL + "userData");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user.getUid()).getValue() == null) {
userRef.child(user.getUid()).setValue(1);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
However database reference doesn't let me add values like this.
You'll need to call push() to generate a unique key for the new data:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference()
mDatabase.push().setValue(1);
This will append the new value at the end of the list.
By combining the push() and child() methods, you can create multiple lists of children in the database:
mDatabase.child("numbers").push().setValue(1);
mDatabase.child("numbers").push().setValue(53);
mDatabase.child("numbers").push().setValue(42);
mDatabase.child("letters").push().setValue("a");
mDatabase.child("letters").push().setValue("z");
mDatabase.child("letters").push().setValue("c");
See the section append to a list of data in the Firebase documentation.
Another post mentioned to check your gradle app file to ensure you have the latest version of the Firebase as follows:
compile 'com.google.firebase:firebase-core:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
I think this should fix many issues that could arise from using older versions.
I hope this helps.
You cannot add anything to the database if you're not authorized. You can do one of the following:
Either set this to your rules tab in firebase console:
{
"rules": {
".read": true,
".write": true
}
}
Or you must create an authentication first (try with email/pass) and create user with
createUserWithEmailAndPassword(email, password)
and then sign in with:
signInWithEmailAndPassword(email, password)
and you need to enable sign-in with email/pass in your console as well.
And then you can write data to your database.
Use push() before set value in the firebase. It will create new user every time when you send value in the database.
Check this sample, it may help you out.
public class FirebaseUserDetails
{
private String mDisplayName;
public String getmDisplayName() {
return mDisplayName;
}
public void setmDisplayName(String mDisplayName) {
this.mDisplayName = mDisplayName;
}
}
Add your value to firebase database,
FirebaseUserDetails firebaseUserDetails = new FirebaseUserDetails();
firebaseUserDetails.setmDisplayName("arunwin");
DatabaseReference pathReference = FirebaseDatabase.getInstance().getReference().child("contacts");
pathReference.child("arun").setValue(firebaseUserDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
And your result value will be added in your database like the below,
contacts:
arun:
mDisplayName:"arunwin"
In my case i am adding new child like this!
NOTE : Here i am adding new child refresh_token to my firebase database
FirebaseDatabase.getInstance().getReference().child("RegistrationModel").child(userId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> stringStringHashMap =(Map<String, String>) dataSnapshot.getValue();
stringStringHashMap.put("refresh_token",refreshedToken);
FirebaseDatabase.getInstance().getReference().child("RegistrationModel").child(userId)
.setValue(stringStringHashMap);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
I'm having some trouble deleting nodes in Firebase
This is how I upload my data
BigBoy add = new BigBoy(addCate);
myRef.push().setValue(add);
This is how i'm trying to delete my data
databaseReference = FirebaseDatabase.getInstance().getReference().child("message");
myRef = database.getReference("message");
String sfasf = Utils.object.getSfasf();
DatabaseReference remove = FirebaseDatabase.getInstance().getReference("message").child(sfasf);
remove.removeValue();
But the problem is that the node is not being deleted.
Make your firebase call like this -
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("message");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
if (dataSnapshots.child("sfasf").exists()) {
dataSnapshots.child("sfasf").removeValue();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
1) You have a reference object but you dont use it. You have created 2 variable references and you dont use them.
2) Your code is wrong in order to remove the node you must specify the key
myRef = database.getReference("message");
myRef.child(key).remove();
---edit---
try this
myRef.child(key).removeValue();
---edit---
From the official documentation:
The simplest way to delete data is to call removeValue() on a reference to the location of that data. You can also delete by specifying null as the value for another write operation such as setValue() or updateChildren(). You can use this technique with updateChildren() to delete multiple children in a single API call.
The problem was that I wasn't referencing the pushID when I was referencing the specific data node. That was solved by saving the key as well when I upload the data.
String userID = user.getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
I have userId of the user so when I'm opening my app for the 2nd time(after signing in) I should not show the select user type layout. So I ve to check whether the use is Customer or Staff internally. So the problem is I ve to check the User Id is there . I couldn't find any method to get whether user Id is there or not! There is method called addListenerForSingleValueEvent but that won't help me in my scenario. Pic of the database is given here
I don't know how to continue after this
mFirebaseDatabase.getReference().child("Users").child("Customers")
To check if an user exists in a particular section of your Firebase database, first you need to add a listener and then use exists() method directly on the dataSnapshot object. So, asumming that Users node is a direct child of the Firebase-database root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference customersRef = rootRef.child("Users").child("Customers").child(userID);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do somethig
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
customersRef.addListenerForSingleValueEvent(eventListener);
DatabaseReference databaseReference=mDatabase;
String queryText="Hotel";
databaseReference.orderByChild("Coupon")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
Here I attached the code which I used to get child names of "Coupon" when I entered the "Hotel" query under the Coupon.But I got blank.I supposed to get Hotel1,Hotel2 object.I'm new to firebase.So hope your support .Thanks in advance.
In the Web version, they use something called ElasticSearch, you could try to read more here: https://firebase.googleblog.com/2014/01/queries-part-2-advanced-searches-with.html
But for Android, I think there isn't any functionality to perform a search like that. What I would do is to query all the records then filter them myself:
DatabaseReference databaseReference = mDatabase;
mDatabase.addValueEventListener(new ValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot val : dataSnapshot.getChildren()){
//I am not sure what record are you specifically looking for
//This is if you are getting the Key which is the record ID for your Coupon Object
if(val.getKey().contains("Hotel")){
//Do what you want with the record
}
//This is if your are querying for the hotel child
if(val.child("hotel").getValue(String.class).contains("Hotel")){
//Do what you want with the record
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
}
Don't load your whole database to filter out needed data. It produces unnecessary traffic which has to be loaded, calculated and deleted. Instead, use:
DatabaseReference myRef = FirebaseDatabase.getDatabaseReference();
Query searchQuery = myRef.child("Coupon").orderByChild("hotel").equalTo("yourSearchString");
To make this code work, you also have to add indexOn on your corresponding attribute in the rules (of Firebase Database console).
I am making my first app using Firebase database. I was able to access the database before, but then I updated my SDKs and couldn't access the Firebase database. This is the function I use
notedatabase = FirebaseDatabase.getInstance();
DatabaseReference mrootDatabaseReference = notedatabase.getReference();
DatabaseReference firstchildref =mrootDatabaseReference.child(initpath);
When I run this it gives getserviceinstance failed error. When I try to debug the program the error states notedatabase= null. I have also changed the rules of my database. How do I fix this?
Sorry, this is my first time asking questions here, if I've left any information out kindly let me know. Thank you.
EDIT : The App works fine now I tried using
String initpath = intent.getExtras().getString("initpath","");
databaseref = FirebaseDatabase.getInstance().getReference();
final DatabaseReference numberofsubjectsRef = databaseref.child(initpath);
Try this one. More details on see an official link.
DatabaseReference databaseTracks;
List<Track> tracks;
databaseTracks = FirebaseDatabase.getInstance().getReference("tracks").child(intent.getStringExtra(MainActivity.ARTIST_ID));
#Override
protected void onStart() {
super.onStart();
databaseTracks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tracks.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Track track = postSnapshot.getValue(Track.class);
tracks.add(track);
}
TrackList trackListAdapter = new TrackList(ArtistActivity.this, tracks);
listViewTracks.setAdapter(trackListAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Okay as you are posting it for first time please make sure this things you have done correctly before making an firebase messaging app using realtime database.
1) you have created a project in firebase and added you project name and package correctly.
2)If in your firebase project rules(as above image) have been defined make sure to provide rules in place of Null it should be true, if you have not opted for any firebase authentication of firebase UI implementation.
3)your Initpath for child should be always same for accessing the same thread of message.
I'm trying since a while to add timestamp on my posts in Firebase, but I'm sadly unsuccessful. I have already tried many advises from stackoverflow, but none worked. Please help me on how to add a timestamp field under each post.
I would to know what's wrong with my code.
final DatabaseReference newPost = mDatabase.push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long timestamp = (Long) dataSnapshot.getValue();
System.out.println(timestamp);
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("username").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabaseUser.setValue(ServerValue.TIMESTAMP);
mProgress.dismiss();
Firebase Database structure:
{
"Blog":{
"-Ke1osQRFVs0fuqx9n18":{
"desc":"again again",
"uid":"FBwMzHJGP4U10LnLOwluy4BVyJ52",
"username":"OziBoo"
}
},
"Users":{
"vi6Qd1AafidNGGV4roBhdLPZYGN2":{
"image":"firebasestorage.googleapis.com/v0/b/agrodesk-b30ff.appspot.com/...",
"name":"Ozi"
}
}
}
There are a lot of error and misuse in your code. Please understand this first:
ref.addValueEventListener(...) is used for listening to every changes made in data referenced by ref
ref.setValue(yourValue) is used to set the value of data referenced by ref object
setValue(...).addOnCompleteListener(...) is used if you want to execute something after value has been updated
If I understand it correctly, all of your sample code you write for writing value into database, right? But you, not knowingly, used addValueEventListener() instead.
So your code to write the value into new child inside "Blog" should be like this:
// Here I use HashMap to make it more simple
// You can (and better to) use your custom object as value container
HashMap<String, Object> value = new HashMap<>();
value.put("title", "your-title");
value.put("desc", "your-desc");
value.put("timestamp", ServerValue.TIMESTAMP);
// ... etc
// the following code will create a reference object pointing at "Blog"
DatabaseReference ref = FirebaseDatabase.getInstance().getRreference("Blog");
// the following code will make a new child inside data referenced by ref (in this case, "Blog")
DatabaseReference newBlog = ref.push();
// the following code is the code that actually update the data of referenced point
newBlog.setValue(value)
// addOnCompleteListener is optional
.addOnCompleteListener(new ... {
// code placed here will be executed when your data is updated
...
});
Hope this helps.
Note:
There I just show you what you want to achieve for this case and this case only. Please read more documentation, guide, and tutorial about Firebase Database. It might take long, but once you understand it, it's actually quite simple.