Firebase Android Database Query (Read Data) - java

I am trying to fetch the data from the firebase database where the valueNum is the contact number with +91. I have shown the same in the screenshot attached but when I am running the code. It gave me a list of all the users even from different valueNum. However, If I pass the incorrect value, giving me the same result i.e. no error.database screen capture
private void funcDatabaseActivity(String valueNum) {
databaseReference.child("users").child("registered-user/" + valueNum).addChildEventListener
(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()) {
UserData data = dataSnapshot.getValue(UserData.class);
Toast.makeText(ContactsActivity.this, "Data Exists - " + data.getDisplayName(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ContactsActivity.this, "Data Not Exists", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

As shown in the screenshot of the database, you are performing an incorrect sequence. I have modified this for you in the answer.
You must take a logical path to access specific information. Also, you can read about ChildEventListener, its uses, and the difference between it and addValueEventListener.
private void funcDatabaseActivity(String valueNum) {
databaseReference= FirebaseDatabase.getInstance().getReference("database-find-me");
databaseReference.child("users").child("registered-user").child(valueNum).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Type here as you like
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(this, "check your internet", Toast.LENGTH_SHORT).show();
}
});
}

Related

Get notifcation when add new data to firebase realtime database

when open the application i want to get notification if new data added to firebase realtime database .
but whan i open the app i got notifcation every time i open the it.
what should i do
this is my code.
cam_firebase.child("Detection").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NotNull DataSnapshot dataSnapshot, String s) {
double longt = dataSnapshot.child("longt").getValue(Double.class);
double lat = dataSnapshot.child("lat").getValue(Double.class);
notify_me();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});

Use RxJava Flowable - how to split the emission according to the type of the event

Let's say we use Firebase ChildEventListener which can be taken as multiple sources of data (its functions) and I'm wrapping it with Flowable or Observable. I want that in each source, the emitter will emit the data to a different pipeline because in each case the data can be changed I want to handle it in different ways - that is, splitting the emission into several different streams according to the type of the event.
How can this be done in Java?
public void newUsers() {
DatabaseReference ref = database.getReference().child("Users");
Flowable.create(emitter -> {
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User userData = dataSnapshot.getValue(User.class);
emitter.onNext(userData);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User userData = dataSnapshot.getValue(User.class);
emitter.onNext(userData);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
User userData = dataSnapshot.getValue(User.class);
emitter.onNext(userData);
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
emitter.onNext(userData);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
User userData = dataSnapshot.getValue(User.class);
emitter.onNext(userData);
}
});
}
}
So, to have multiple streams, we can't have a single Flowable. I dunno whether a Flowable is actually a requirement, so i'll just outline my idea, you feel free to correct it and adapt to your needs.
BehaviourSubject childAddedStream;
BehaviourSubject childChangedStream;
BehaviourSubject childRemovedStream;
BehaviourSubject childMovedStream;
BehaviourSubject cancelledStream;
public void newUsers() {
DatabaseReference ref = database.getReference().child("Users");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User userData = dataSnapshot.getValue(User.class);
childAddedStream.onNext(userData);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User userData = dataSnapshot.getValue(User.class);
childChangedStream.onNext(userData);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
User userData = dataSnapshot.getValue(User.class);
childRemovedStream.onNext(userData);
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
childMovedStream.onNext(userData);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
User userData = dataSnapshot.getValue(User.class);
cancelledStream.onNext(userData);
}
});
}
}
something like this would be my starting point.
The idea is for this class to initialize different Subjects for each callback, register the callback to the FirebaseDatabase when it's created, and route the individual callbacks to different streams (subjects, feel free to use a more relevant Subject that BehaviourSubject if you want) - then whoever needs to listen just listens for the relevant stream instead of the single Flowable which simply acts like a bridge between the callback and reactive world.

How to check if value exists in firebase databse

I have this Database:
I want to find out if a Email (value in database) already exists. So I have to iterate through each child of "email" and check if the value equals to the String inputMail.
I tried the following Code, but It doesn´t work, can anybody help me please? Thank u
final String input_mail = et_email.getText().toString();
DatabaseReference email = FirebaseDatabase.getInstance().getReference().child("email");
email.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String emailVal = ds.getValue(String.class);
if (emailVal.equals(input_mail)) {
//Toast exists
}
else {
//Toast not exists
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In conclusion if I enter person1#m.de it should give out a toast that it exist
Here is a very easy way . Make your email as child . You have to replace the dot from the email and set it as child. (you can't use the email directly to a child)
static String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
static String decodeUserEmail(String userEmail) {
return userEmail.replace(",", ".");
}
Then you can easily match it like this :
final String input_mail = et_email.getText().toString();
DatabaseReference email = FirebaseDatabase.getInstance().getReference().child("email");
email.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(datasnapshot.child(input_mail).exits){
//Toast exists
}else {
//Toast not exists
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Model Class returns null

[model class is returning null, data is coming from Firebase database but upon getting imageUrl its giving null.
Actually, I am trying to get images urls from database which are previously saved.
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getInstance().
getReference("Catagories");
mupload=new ArrayList<>();`
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot post : dataSnapshot.getChildren())
{
Upload upload=post.getValue(Upload.class);
mupload.add(upload);
}
customQuoteAdapter=new CustomQuoteAdapter( Images.this,
mupload);
recyclerView.setAdapter(customQuoteAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(),
"ERROR"+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
You have a bussiness (sic) level in your JSON, that you're not handling in your code. The simplest way to fix this is to attach your listener to that bussiness node:
databaseReference=firebaseDatabase.getInstance().getReference("Catagories/Bussiness");
mupload=new ArrayList<>();`
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot post : dataSnapshot.getChildren()) {
Upload upload=post.getValue(Upload.class);
mupload.add(upload);
}
customQuoteAdapter=new CustomQuoteAdapter( Images.this, mupload);
recyclerView.setAdapter(customQuoteAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR"+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
If you want to get all URLS for all nodes under Categories, you'll need to add a loop inside onDataChange. Something like:
databaseReference=firebaseDatabase.getInstance().getReference("Catagories");
mupload=new ArrayList<>();`
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot categorySnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot linkSnapshot : categorySnapshot.getChildren()) {
Upload upload=linkSnapshot.getValue(Upload.class);
mupload.add(upload);
}
}
customQuoteAdapter=new CustomQuoteAdapter( Images.this, mupload);
recyclerView.setAdapter(customQuoteAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR"+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Should it be?
public String getImageUrl() {
return this.imageUrl;
}

How to get all child's data in firebase and show it into my android app?

I have this structure in my Firebase Real-time database :
How can I count the data and show it in my app, which listener shall I use to get all childrens?
There are a few ways in which you could achieve this.
I use the following way:
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
YourObject object = dataSnap.getValue(YourObject.class);
// Use your object as needed
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dataSnapshot returns the child referenced. Once you have it, all you have to do is iterate through them and you have access to "all children" as you wanted.
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
/** Qty of data in demografi, this is what you want. */
long Count = dataSnapshot.getChildrenCount();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you want to monitor the count of data in realtime way,
you have to replace [addListenerForSingleValueEvent] with [addValueEventListener].
I will prefer this way -
String email, gender, nama;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("demografi");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// To get children count
dataSnapshot.getChildrenCount();
email = dataSnapshot.child("email").getValue().toString();
gender = dataSnapshot.child("gender").getValue().toString();
nama = dataSnapshot.child("nama").getValue().toString();
// and so on..
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s){
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you don't have a model class, you can simply use the String class. So to get all child's data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference demografiRef = rootRef.child("demografi");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nama = ds.child("nama").getValue(String.class);
Log.d("TAG", nama);
}
Log.d("TAG", String.valueOf(dataSnapshot.getChildrenCount()));
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
demografiRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be all the names of all your users. As you can see, there is a second log statement which will print the total number of your children.

Categories