Sorting in ascending order not working Firebase - android

Hey I am trying to sort my data in ascending order but the data is getting displayed in the order of how they are stored in the database:
This is the function being used to sort the data to find the least time.
private void getTimeTaken1(final String name) {
final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("users");
final Query query = databaseReference1.orderByChild("timeTaken").limitToLast(10);
Log.e(TAG, "getTimeTaken1: " + name);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int rank = 1;
for (DataSnapshot userAnswerSnapshot : dataSnapshot.getChildren()) {
if (yourTimeArraylist.size() < 10) {
if (userAnswerSnapshot.child("questions").child(name).hasChild("timeTaken")
&& userAnswerSnapshot.child("questions").child(name).child("checkAnswerCorrect").getValue(String.class).equals("1")) {
Log.e("", "User " + " " + userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue().toString());
yourTimeArraylist.add(new PreviousDayRank(userAnswerSnapshot.child("random").getValue(String.class),
userAnswerSnapshot.child("name").getValue(String.class),
timetaken(userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue(Integer.class)),
rank));
Log.e("", "onDataChange: user" + userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue());
rank++;
} else {
yourTimeArraylist.add(new PreviousDayRank(userAnswerSnapshot.child("random").getValue(String.class), userAnswerSnapshot.child("name").getValue(String.class), "-", rankl̥));
rank++;
}
}
}
query.removeEventListener(this);
databaseReference1.removeEventListener(this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Your DatabaseReference is wrong. Please use this code:
final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("users").child(userId).child("questions").child(questionNumber);
final Query query = databaseReference1.orderByChild("timeTaken").limitToLast(10);
Where userId and questionNumber are the id's generated by push() method and the second by you.
Hope it helps.

Related

Android Firebase, Get position of key in node

I want to get data according to user's ranking. First order by user's points and get users position in node. But I can't think of the way to implement this.
First This is my firebase 'users' node
Maybe It will be like 'databaseRef.child("users").orderByChild("points")...'
I don't know from here.
ps. It's not get nth item. It's 'where is the item' ( item's nth )
Thank you!
This can be done by adding a ctr in you dataSnapshot loop
myRef = FirebaseDatabase.getInstance().getReference().child("users");
final Query query = myRef.orderByChild("points");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = dataSnapshot.getChildrenCount();
int i = 0;
// loop through dataSnapshot
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String nickName = childSnapshot.child("nickName").getValue(String.class);
if (nickName.equals(mUser.getNickName()) {
//when nickName would match
int userPlace = total - i;
int points = childSnapshot.child("points").getValue(Interger.class);
//do something here
break;
} else {
i++;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Kindly read
Retrieving Data.
How Data is Ordered
The callback function receives a DataSnapshot, which is a snapshot of
the data. A snapshot is a picture of the data at a particular database
reference at a single point in time. Calling val() / getValue() on a
snapshot returns the a language-specific object representation of the
data. If no data exists at the reference's location, the snapshot's
value is null.
If you want to get all points then check this LOGIC.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("products");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Integer> points = new ArrayList<>();
for (Map.Entry<String, Object> entry : products.entrySet()){
Map singleUser = (Map) entry.getValue();
points.add((Integer) singleUser.get("points"));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
I solve this problem. Android_K.Doe's answer is right. I add some code in his code. Because Firebase database does not give descending query.
final Query query = databaseReference.child("users").orderByChild("points");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
int all = (int) dataSnapshot.getChildrenCount();
Log.d(TAG, "all: " + all);
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String nickName = ds.child("nickName").getValue(String.class);
if (nickName.equals(user.getNickName())) {
Log.d(TAG, "nickName: " + user.getNickName());
int userPlace = i;
Log.d(TAG, "position: " + userPlace);
myInfoRankingNumTxt.setText(Integer.toString(all - (i)) + "위");
break;
} else {
i++;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Android Retrieving Single Value from FireBase-RealTime Database

Answer needed urgently. I'm trying to retrieve a single value school name as marked in the snapshot attached below and populate it to my android spinner from my firebase-database
private class FireBaseConnection{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference rootRef = database.getReference().child("root");
DatabaseReference reg_schools = rootRef.child("reg_schools");
}
private ArrayList<String> retrieveAllSchools(){
pBar.setMessage("Please Wait..Retrieving Schools...");
pBar.show();
FireBaseConnection fireBaseConnection = new FireBaseConnection();
String key = fireBaseConnection.reg_schools.push().getKey();
fireBaseConnection.reg_schools.child(key).child("school_name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
resultProcessorObject = snapshot.getValue(SchoolObject.class);
schools_retrieved = resultProcessorObject.getSchool_name();
schools.add( schools_retrieved);
//schools = (ArrayList<Object>) snapshot.getValue();
// Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
pBar.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return schools;
}
So I want to answer my question..I made it work with the help of #Alex Mamo video
so everything remained unchanged..all i did was tweak my code a bit
Instead of
fireBaseConnection.reg_schools.child(key).child("school_name").addValueEventListener(){
//Then my codes here
}
Instead i did
fireBaseConnection.reg_schools.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
resultProcessorObject = snapshot.child("school_name").getValue(String.class);
//schools_retreived = resultProcessorObject.getSchool_name();
schools.add(resultProcessorObject);
count = dataSnapshot.getChildrenCount();
Toast.makeText(Main2Activity.this, "Total number of " + count + " schools were retreived ", Toast.LENGTH_SHORT).show();
// schools = (ArrayList<Object>) snapshot.getValue();
// Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
pBar.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So Basically i used the snapshot to reference the node "school_name" i'm looking for in the onDataChange Method

Search Data from firebase database in android

Hello I am trying to search data from firebase database. But I don't see there any option for search data from firebase. In my firebase database, there are address, city and mobile number that are present. I want to search data from that if I enter mobile number last digit. I want to get result that mobile number.
Here is my code
floating_search_view_recruiter = (FloatingSearchView) findViewById(R.id.floating_search_view_recruiter);
floating_search_view_recruiter.setSearchHint("Search Recruiter..");
floating_search_view_recruiter.attachNavigationDrawerToMenuButton(drawer);
floating_search_view_recruiter.setOnMenuItemClickListener(new FloatingSearchView.OnMenuItemClickListener() {
#Override
public void onActionMenuItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_filter) {
aleartDialogFilter();
}
}
});
fab_recyclerView.setVisibility(View.GONE);
floating_search_view_recruiter.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
#Override
public void onSearchTextChanged(String oldQuery, String newQuery) {
//recruiterAdapter.getFilter().filter(newQuery);
mRef.orderByChild("city")
.startAt(newQuery)
.endAt(newQuery + "\uf8ff");
mRef.child("city").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
Please refer this github repository for more examples
enter link description here
mDatabase = FirebaseDatabase.getInstance().getReference().child("appointment");
            Query query = mDatabase.orderByChild("patient").equalTo(restoredText.toString());
            query.addValueEventListener(new ValueEventListener() {
                #Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot != null || dataSnapshot.getChildrenCount() > 0) {
                        collectPhoneNumbers((Map<String, Object>) dataSnapshot.getValue());
                    }
                }
                #Override
                public void onCancelled(DatabaseError databaseError) {
                    // Failed to read value
                    Toast.makeText(getApplicationContext(), "Failed to read value." + databaseError.toException(), Toast.LENGTH_LONG).show();
                }
            });
private void collectPhoneNumbers(Map<String, Object> users) {
        if (users != null && !users.isEmpty()) {
            contacts.clear();
            contacts.add(new Appointment("<b>Date</b>", "<b>Time</b>", "<b>Doctor Name</b>", "<b>Patient Name</b>"));
            //iterate through each user, ignoring their UID
            for (Map.Entry<String, Object> entry : users.entrySet()) {
                //Get user map
                Map singleUser = (Map) entry.getValue();
                //Get phone field and append to list
                String date = (String) singleUser.get("date");
                String time = (String) singleUser.get("time");
                String doctor = (String) singleUser.get("doctor");
                String patient = (String) singleUser.get("patient");
                contacts.add(new Appointment(date, time, doctor, patient));
// Toast.makeText(getApplicationContext(), "Date: " + date + ", Time:" + time + ", Doctor:" + doctor + ", Patient:" + patient, Toast.LENGTH_LONG).show();
                adapter.notifyDataSetChanged();
            }
        }
    }

I have the following firebase database and i am not able to retrieve the details like name,address,no

The following is an image from firebase database and i am not able to retrieve the data.
MainActivity.java
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
FirebaseData pg=dataSnapshot.getValue(FirebaseData.class);
Log.d(TAG, "Value is: " + value);
Toast.makeText(MainActivity.this,value,Toast.LENGTH_SHORT).show();
}
FirebaseData.java class
public class FirebaseData {
public String name;
public String address;
public String pgid;
public String contact_no;
public FirebaseData() {
// Needed for Firebase
}
public FirebaseData(String address, String name, String contact_no) {
this.name = name;
this.address = address;
this.contact_no=contact_no;
}
To get the address, contact_no and the name from HSRLayout node please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference HSRLayoutRef = rootRef.child("cities").child("Bangalore").child("localities").child("HSRLayout");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String address = dataSnapshot.child("1").child("address").getValue(String.class);
String contact_no = dataSnapshot.child("1").child("contact_no").getValue(String.class);
String name = dataSnapshot.child("1").child("name").getValue(String.class);
Log.d("TAG", address + " / " + contact_no + " / " + name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
HSRLayoutRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
das / 15615446484 / HSR
If you want to get the data from multiple childs, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference HSRLayoutRef = rootRef.child("cities").child("Bangalore").child("localities").child("HSRLayout");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String address = ds.child("address").getValue(String.class);
String contact_no = ds.child("contact_no").getValue(String.class);
String name = ds.child("name").getValue(String.class);
Log.d("TAG", address + " / " + contact_no + " / " + name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
HSRLayoutRef.addListenerForSingleValueEvent(eventListener);
In Database check Rules and set
{ "rules": {
".read": true,
".write": true}}

How to retrieve particular data from firebase?

While retrieving the data I am using this code
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Firebasemodel firebasemodel = data.getValue(Firebasemodel.class);
firebasemodels.add(firebasemodel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});`
This code snippet which returns the complete data of firebase database.
But I want to retrieve the complete data of particular users. How do I achieve it?
Thanks in advance
Try code below:
FirebaseDatabase.getInstance().getReference().child("notepad-secure/notepad").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
while (dataSnapshots.hasNext()) {
user = dataSnapshotChild.getValue(User.class);
users_list.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Error", "---" + databaseError.getMessage());
}
});
Model class:
public class User {
public String id;
public String note;
public String tittle;
public User() {
}
public User(String id, String note, String tittle) {
this.id= id;
this.note= note;
this.tittle= tittle;
}
}
And Declare
List<User> users_list;
User user;
Please use this code for getting all data:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String id = ds.child("id").getValue(String.class);
String note = ds.child("note").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String user = ds.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + users);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
And your output will be:
-Kono2LMSe... / sadsad / sadsad / NK46X......
If you want to retrieve only specific data, please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child("NK46...");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = ds.child("id").getValue(String.class);
String note = ds.child("note").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String user = ds.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + users);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
It will work for sure.

Categories

Resources