How to use multiple orederbychild in Firebase database? - android

Hello Everyone I am using firebase database in my app. I am able to add data to database. Now I want to implement search in my app, I have two option for search users,
1)Blood Group
2)User Area
I am able to get data as per blood group selection, but I don't know how can I fetch data with blood group and area. (Multiple Selection Filter)
Now if the user will select 'A+' as blood group from spinner and select Area 'ABC'
Then result would come as Users with 'A+' blood group and 'ABC' area.
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Default Selected"+sel_blood_group);
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Your Logic here
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
UserRegisterModel mModel = eventSnapshot.getValue(UserRegisterModel.class);
// Log.e("DATA" ,""+ mModel.getName());
}
Query chatRoomsQuery = mFirebaseDatabase.orderByChild("blood_group").equalTo(sel_blood_group);
chatRoomsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
UserRegisterModel mModel = issue.getValue(UserRegisterModel.class);
Log.e("QUERY DATA" ,""+ mModel.getName());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("DATA" ,""+ chatRoomsQuery.toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});

Firebase RealTime Database does not support multiple where clauses. So try to query with one filter and then filter the next one programatically.
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Default Selected"+sel_blood_group);
System.out.println("Default Selected"+sel_area);
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Your Logic here
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
UserRegisterModel mModel = eventSnapshot.getValue(UserRegisterModel.class);
// Log.e("DATA" ,""+ mModel.getName());
}
Query chatRoomsQuery = mFirebaseDatabase.orderByChild("blood_group").equalTo(sel_blood_group);
chatRoomsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
UserRegisterModel mModel = issue.getValue(UserRegisterModel.class);
if(mModel.getArea().equals(sel_area))
Log.e("QUERY DATA" ,""+ mModel.getName());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("DATA" ,""+ chatRoomsQuery.toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});enter code here

You can make userName to be added only once using the following method. I have assumed that you are storing the user details in UserRegisterModel class. Please take care of the DatabaseReferences as I have used what you have mentioned and I am not aware of your Database structure.
Query chatRoomsQuery = mFirebaseDatabase.orderByChild("User_Name").equalTo(userRegisterModel.getUserName());
chatRoomsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.e("UserAlready Registered");
}
else
{
mFirebaseDatabase.push().setValue(userRegisterModel);;
Log.i("User added Successfully");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have not tested the code but I think it will work! :)

Related

Retrieve list of Firebase database data with rxjava

I am creating an android app using firebase. My firebase database structure is as follow-
Users:{
uid:{
name:Bruno,
age: 22,
email: bruno#gmail.com,
address:...
}
},
Level_info:{
uid:{
score:70,
level:5
}
}
Before Rxjava, I retrieve all users like this-
userRef.addValueEventListener(new ValueEventListerner(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot.getChildren())
{
User user = snapshot.getValue(User.class);
userList.add(user);
//to get score and levels
/*I can't add nested value event listener directly because of Asynchronous behavior */
userId.add(user.getId());
}
getLevels(userId);
}
#Override
public void onCancelled(DatabaseError error) {
//handle errors
}
});
void getLevels(final ArrayList<String> userid){
levelRef.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(String id:userid)
{
Level level = dataSnapshot.child(id).getValue(Level.class);
levelList.add(level);
}
/** Attch both "userList" and "levelList" to RecyclerView */
}
#Override
public void onCancelled(DatabaseError error) {
//handle errors
}
});
}
It goes fine.But if there are many nested Listeners, It will hard to read.So I tried to change to RxJava and RxAndroid. Like this-
public Observable<ArrayList<User>> userOb(){
return Observable.create(new
ObservableOnSubscribe<ArrayList<User>>() {
#Override
public void subscribe(final
ObservableEmitter<ArrayList<User>> emitter)
throws Exception {
FirebaseDatabase.getInstance().getReference("Users")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ArrayList<UserModel> listUsers;
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
listUsers= new ArrayList<>();
listUsers.add(user);
emitter.onNext(listUsers);
}
emitter.onComplete();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
Here I don't know how to zip with LevelObservable because levelObservable need UserId from UserObservable to get data from Levels/(uid)/"level_info" .May be this is stupid question but I am new to RxJava. I want to get Corresponding userId from UserObservable to LevelObservable. So how can I do that?
Sorry for my bad English Writing skill.
Edit: Is there some ways to implement like this (because may be I miss some easy ways to implement).

how to get URI of an image from Datasnapshot

I am making an app where I can upload images to firebase then retrieve them and view them in a viewpager.
The images have a name and an url.
In addition to that, I want to be able to write the name of the image in a textbox and display the corresponding image in an imageview.
This is the code I'm working with :
private void findImage(){
final Query query = mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
//i have tried this first but i don't know what method i should use to get the URI from the datasnapshot.
image.setImageURI(NamedImage.getValue());
//then i have tried this but i can't use "context" here, nor can i apply .getImageUrl to the datasnapshot.
Glide.with(context).load(NamedImage.getImageUrl()).into(image);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I am new to android studio and java and I haven't studied it before starting this application.
Any idea on what I should do please?
I found the solution to my problem :
private void findImage(){
final Query query = mDatabaseRef.orderByChild("name").equalTo(EditTextName.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot NamedImage : dataSnapshot.getChildren()) {
SliderUtils sliderUtils = NamedImage.getValue(SliderUtils.class);
Glide.with(getApplicationContext()).load(sliderUtils.getImageUrl()).into(image);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

firebase gets data too many times

I used recyclerview, arraylist, and firebase to get and show data, but data is added to the list too many times..
This is my code
database=FirebaseDatabase.getInstance();
mRef=database.getReference("SETS");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot==null) return;
for(DataSnapshot userSanpshot : dataSnapshot.getChildren())
{
if(userSanpshot.child("DETAIL").getValue()==null) break;
single.Detail=userSanpshot.child("DETAIL").getValue().toString();
/~/
list.add(single);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adapter.setItems(list);
and this is my code when I send data to firebase
Button sharebut=(Button)findViewById(R.id.usersend);
sharebut.setOnClickListener(
new FloatingActionButton.OnClickListener() {
#Override
public void onClick(View view) {
mDatabase.child("SETS").child(userId).child("DETAIL").setValue(detailText.getText().toString());
/~/
finish();
}
}
);
}
Try Using this method
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do here your work
}
#Override
public void onCancelled(DatabaseError databaseError) {
// handle error here
}
});

Firebase join using Android Studio

I need to do join operation for data using the unique key provided by the Firebase database.Table habitat is created under the unique key of snake table.And also need to retrive data for list view or recyclerview.
databaseSnake = FirebaseDatabase.getInstance().getReference()
.child("snake")
.orderByKey()
.addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot child : dataSnapshot.getChildren())
{
// HERE CORRESPONDS TO JOIN
DatabaseReference Databasesnake = FirebaseDatabase.getInstance().getReference()
.child("habitat")
.orderByKey()
.addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
// repeat!!
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}

Extract child's name from DatabaseReference in Google Firebase

I want to extract the names (strings) of all the childs of mUsrRef.
DatabaseReference mUsrRef;
public void read_child() {
mUsrRef = mUsersRef.child("user_name");
// ...
}
How can I do it?
You can use DataSnapshot.getChildren() for that:
public void read_child() {
mUsrRef = mUsersRef.child("user_name");
mUsrRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, childSnapshot.getKey());
}
}
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
}
You must add a listener. For instance :
mUsrRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren() ) {
child.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.

Categories

Resources