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();
}
}
}
Related
I am trying to get a list of my last active users in my app. I am storing the UIDs of them as a string in my database it's as follow in the database:
lastActiveUsers:uid1 uid2 ... etc.
Now I need to show a list of the users with the UIds in this string but when using nested listener I don't know how to do that this is my code :
this is my code :
public void getStudents() {
if (!list.isEmpty()) {
list.clear();
}
lastActiveUsersReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lastActiveUsers = (String) dataSnapshot.getValue();
final String[] lastActiveUsersArray = lastActiveUsers.split(" ");
for(final String userId : lastActiveUsersArray){
usersReference.orderByKey().equalTo(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String localCurrentUserUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = new User();
String points = "";
boolean admin = false, online = false;
String name = (String) dataSnapshot1.child("userName").getValue();
String email = (String) dataSnapshot1.child("userEmail").getValue();
String uid = dataSnapshot1.getKey();
if (dataSnapshot1.child("points").getValue() != null)
points = dataSnapshot1.child("points").getValue().toString();
String imageUrl = (String) dataSnapshot1.child("userImage").getValue();
String userType = (String) dataSnapshot1.child("userType").getValue();
if (dataSnapshot1.child("admin").getValue() != null)
admin = (boolean) dataSnapshot1.child("admin").getValue();
if (dataSnapshot1.child("online").getValue() != null) {
online = (boolean) dataSnapshot1.child("online").getValue();
/*if(online)
onlineUsersIndexes.add(list.size());//TODO : try to add this after solving its problem*/
}
int pointsInt;
try{
pointsInt = Integer.parseInt(points);
}
catch (Exception ex){
Log.v("pointsException", "exception is : " + ex);
pointsInt = 0;
}
Log.v("Sizee", "array size : " + lastActiveUsersArray.length
+ " , userId : " + userId + " , array : " + lastActiveUsersArray.toString());
if (userType.equals("طالب") && !uid.equals(localCurrentUserUid) && !inList(userId) && !online && name != null) {//TODO : think about allowing challenges against teachers and others and ask my friends about thier opinions in that
user.setAdmin(admin);
user.setOnline(online);
user.setName(name);
user.setPoints(pointsInt);
user.setImageUrl(imageUrl);
user.setEmail(email);
user.setUid(uid);
list.add(user);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Toast.makeText(ChallengersActivity.this, "list size is : " + list.size(), Toast.LENGTH_SHORT).show();
recyclerAdapter.notifyDataSetChanged();
if (progressBar.getVisibility() != View.GONE)
progressBar.setVisibility(View.GONE);
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
if (list.size() == 0) {
noStudentsTv.setVisibility(View.VISIBLE);
noInternetConnectionText.setVisibility(View.GONE);
} else {
noStudentsTv.setVisibility(View.INVISIBLE);
noInternetConnectionText.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
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
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.
I am having problem in retrieving data from firebase. I have one root user's node and then inside that root I have one userID child node. Inside that child node I am storing user information according to its blood group.
Now, what I want is to fetch the name and email according to blood group, say fetch all user data whose blood group is B+.
Also, please tell me on how to fetch all entries in the firebase and show on textView.
//show data on text view
datashow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("inside click", "onClick: ");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference db = database.getReference();
db.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Iterable<DataSnapshot > children = dataSnapshot.getChildren();
Log.i("children", "onDataChange: " + children);
for(DataSnapshot child : children)
{
Map<String , String> map = (Map)child.getValue();
Log.i("inside", "onDataChange: " + map);
name = map.get("name");
email = map.get("email");
dateof = map.get("userDob");
showData(name , email , dateof );
Log.i("datasnap", "onDataChange: data snapshot " + name + email + dateof);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
this is my snapshot for Firebase database
enter image description here
db.child("users").orderByChild("userBloodGroup").equalTo("B+").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
List<User> data = new ArrayList<>();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot :
dataSnapshot.getChildren()) {
User element = snapshot.getValue(User.class);
element.setKey(snapshot.getKey());
data.add(element);
}
for (User user: data){
Log.i(TAG,"user name: " +user.getName());
Log.i(TAG,"user email: " +user.getEmail());
Log.i(TAG,"user dob: " +user.getUserDob());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
To query for all users with the bloodGroup B+, use a Firebase Query:
firebaseReference("users").orderByChild("userBloodGroup").equalTo("B+")
To get all the data of the users, you could use a Listener to get all of them and put them in whatever TextView you need. You could check the documentation on Firebase on how they read data. https://firebase.google.com/docs/database/android/read-and-write
I'm trying to get a value from the Firebase.
I am using this piece of code to get that, but all the methods I call on score1 return null.
private void onSignedInInitialize(String username) {
mUsername = username;
final DatabaseReference reference = mFirebaseDatabase.getReference();
Query query = reference.child("scores").orderByChild("username").equalTo(mUsername);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Score scores1 = dataSnapshot.getValue(Score.class);
Log.d(TAG, " scores1 " + scores1 + " datasnapshot to String " + dataSnapshot.getValue().toString());
Log.d(TAG, " user " + scores1.getUsername());
Log.d(TAG, " user " + scores1.getUsername());
scoresTextView.setText(scores1.getScore());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
My Firebase structure looks like this
I used the example in their documentation (with Post class) and also searched on Google but i can't find how I can get the value of scores.
Thank you for your answer.
This is Score class
public class Score {
private String username;
private String score;
public Score() {
}
public Score(String username, String score) {
this.username = username;
this.score = score;
}
public String getUsername() {
return username;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
As your database image shows, the database nodes that are instances of Score are children of location scores. Update your code as shown below.
A second problem is that the score in the database is an integer, not a String as your Score class expects. You must either update the DB to contain strings or change Score to handle score as an integer. Also, your Score class is missing a setter method for username.
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
if (dataSnapshot.exists()) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Score scores1 = snap.getValue(Score.class);
Log.d(TAG, " scores1 " + scores1 + " datasnapshot to String " + dataSnapshot.getValue().toString());
Log.d(TAG, " user= " + scores1.getUsername());
Log.d(TAG, " score= " + scores1.getScore());
scoresTextView.setText(scores1.getScore());
}
} else {
Log.e(TAG, "onDataChange: NO DATA");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled: " + databaseError.getMessage());
}
});