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.
Related
Hi I'm new in firebase and android studio and I have a problem
I want to store the data of this database in an array and next use the array to make a recycler view
Then in the main activity I wrote this:
And if I run the app only this is shown:
But if I do the same but instead of firebase i use a String[] with the data i want to show it works but i don't know why with firebase i can't.
if I change the references by this:
reference = database.getReference(FirebaseReferences.POKEMONS_REFERENCES);
reference.child(FirebaseReferences.APP_REFERENCES).addValueEventListener(new ValueEventListener() {
when I run the app, it automatically closes and i don't know what to do.
Could you please tell me what i'm doing wrong?
Thank you in advance.
Here is the logCat
https://github.com/adcasna/SearchViewPrueba2/wiki
Fisrts of all, please note that the Firebase documentation recommends against using arrays. Using an array is an anti-pattern when it comes to Firebase. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write. If you still want to use this kind of structure, for getting those names and store them in an ArrayList, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference appRef = rootRef.child("pokemons").child("app");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String c_name = ds.child("c_name").getValue(String.class);
list.add(c_name);
Log.d("TAG", c_name);
}
Log.d("TAG", list );
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
appRef.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 have the following data structure on firebase for the user MF0qeRA4p7djfjgXxqwFOck3m6p02. I want to get the value of item3 to populate a single field into the User interface on an Android App. I have been looking through samples on Stackoverflow, but all I have found are outdated and do not work with the current version of firebase. I'm new to firebase completely and this is my first app on android. I've got the oncreate user method to populate the users email address and add the 4 item fields, but retrieving the data I'm completely lost and I am not sure where to even begin.
-Users
---MF0qeRA4p7djfjgXxqwFOck3m6p02
------item1:"1"
------item2:"2"
------item3:"3"
------item4:"4"
According to what I can identify is, you are facing problem retrieving data from this reference. Here is the code:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.child("MF0qeRA4p7djfjgXxqwFOck3m6p02").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map=(Map<String, Object>)dataSnapshot.getValue();
String item3=(String)map.get("item3");
display(item3);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.
You can create a custom model and inside you can insert elements. Something like this:
public class Item {
private List<Object> ojects;
}
There you can save instance of Item on database. In this case you have more controll. Other case is to use push() method, that will generate a new encoded key, something like this:
mDatabase.child("items").push().put(new Object());
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) {
}
});
I am using Firebase realtime database in Android app, and have data like this:
How can i delete the record "Apple" (marked in picture)?
According to the docs, to remove an item you call removeValue() on the reference. But to get the reference i require the child id. Because its a random generated id (-KISNx87aYigsH3ILp0D), how to delete it?
If you don't know the key of the items to remove, you will first need to query the database to determine those keys:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("firebase-test").orderByChild("title").equalTo("Apple");
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
appleSnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
this solved my problem
mPostReference = FirebaseDatabase.getInstance().getReference()
.child("quotes").child(mPostKey);
mPostReference.removeValue();
If you are using firebase-admin you can simply try this out as
admin.ref(`/users/${userid}`).remove()
and that works for me.
And also do remember to use async and await syntax.
You can use this code :
onDeletePost(id:string){
return this.http.delete(`https://my-angular8-prjt.firebaseio.com/posts/${id}.json`).subscribe();
}
Depending on how and why you are deleting the data you can use these:
// Could store the push key or get it after push
String newPostKey = yourDatabase.child('firebase-test').push({
something:something
}).key();
// Depends how you get to here
howYouGotHereId.parent().setValue(null);
Firebase Save Data 3.0
Assume that images is the directory of your firebase database which you want to clear.
private static DatabaseReference mDatabase;
public static void clearData(){
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("images").setValue(null);
}
Here images is the parent directory of the database. If you want to clear a nested directory (DCIM) inside the images directory so that you can retain the remaining data in it.
In that scenario you can do like this,
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("images").child("DCIM").setValue(null);
As a response to the query, Please try to use setValue method with null value setValue(null) to clear the data from firebase database
In the case of Firebase admin with python though:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
cred = credentials.Certificate("<your certificate>.json")
firebase_admin.initialize_app(cred, {'databaseURL': 'https://<your db>.firebaseio.com/'})
snapshot = db.reference('firebase-test').get()
for k,v in snapshot.items():
if v['title'] == "Apple":
db.reference('firebase-test').child(k).delete()