so honestly I just feel stupid right now but I just don't get it...
I want to get one "User" Object from my Firebase Realtime Database, so I add an ValueListener, right?
I have a Method "getUser" which has "User" as returnvalue. In there I use this:
ValueEventListener valueListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildren())
{
User u = snap.getValue(User.class);
if(u.getEmail().equals(userEmail))
{
//user = u;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
//Adding the Listener for Single Event
fref.child("User").addListenerForSingleValueEvent(valueListener);
//Using "u" here then
Now I don't see a good way get that User "u" out of there, how do I get it?
I know this should be basics, but I just don't get it..
thanks in advance :)
what about:
private User targetUser;
#Override
protected void onStart() {
super.onStart();
final ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userNameList = new ArrayList<>((ArrayList) dataSnapshot.getValue());
for (User u : userNameList) {
if (u.getEmail().equals(userEmail)) {
targetUser = u;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled: Failed to load User list.");
}
};
userlistReference.addValueEventListener(userListener);
mUserListListener = userListener;
//use targetUser reference but check if it is null(can be null)...
}
You have to use a CountDownLatch - this object will let you wait till the listener is actually invoked before returning the object :
private User getUser() {
final User user = null ;
final CountDownLatch cdl = new CountDownLatch(1);
ValueEventListener valueListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildren())
{
User u = snap.getValue(User.class);
if(u.getEmail().equals(userEmail))
{
user = u;
break ;
}
}
cdl.countDown();
}
#Override
public void onCancelled(DatabaseError databaseError) {
cdl.countDown();
}
};
//Adding the Listener for Single Event
fref.child("User").addListenerForSingleValueEvent(valueListener);
try {
cdl.await();
} catch (InterruptedException ie) {
}
return user ;
}
You just need to create global variable on your class, like:
private User myUser;
Then inside your listener just do:
myUser = u;
This is the easiest way...
Related
I have the following Firebase DB node structure:
UserInGroup
--- GroupID
--- UserId : true/false
Users
--- UserId
--- Username : String
--- ...
GroupStatus
--- GroupId
--- UserId: true/false
I need to pull for the first node to get all the users in the Group
Then use that info to get the users account info details
Finally check to see the users status in the Group
I cannot figure a way to implement the completionhandler in Java/Android ? I have done so for iOS with completionhandlers.
Can anyone assist with helping me implement the solution in Java?
---- UPDATE ----
I have done the following:
// Create an interface to init all the callback functions
private interface AllUsersCallback {
void onSuccess(DataSnapshot dataSnapshot);
void onStart();
void onFailure();
}
private void readData(Query query, AllUsersActivity.AllUsersCallback listener) {
listener.onStart();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
listener.onSuccess(dataSnapshot);
} else { // dataSnapshot doesn't exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
//
listener.onFailure();
}
});
}
And lastly the Activity view:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Init ArrayList
userList = new ArrayList<>();
userInGroupReference = mFirebaseDatabase.getReference("GroupUsers");
userInGroupQuery = userInGroupReference.child(groupID).orderByValue().equalTo(true);
// Completion Handler for Lookups
readData(userInGroupQuery, new AllUsersActivity.AllUsersCallback() {
#Override
public void onSuccess(DataSnapshot dataSnapshot) {
// Clear the List (remove dupes)
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String userId = snapshot.getKey();
// Call function to set usernames to the users
setUsername(userId);
}
/*
THIS ALWAYS COMES OUT BLANK!? <--------
*/
for (int i = 0; i < userList.size(); i++) {
Log.e(TAG,"List element: " + userList.get(i).getUsername());
}
}
#Override
public void onStart() {
// When starting
Log.d("ONSTART", "Started");
}
#Override
public void onFailure() {
// If failed
Log.d("onFailure", "Failed");
}
});
}
and the function used to set the users username to the userList:
public void setUsername(String userId) {
userReference = mFirebaseDatabase.getReference("Users");
userQuery = userReference.child(userId).child("username");
// Add handle for listener
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String username = dataSnapshot.getValue().toString();
AllUsers result = new AllUsers(username);
userList.add(result);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
These database calls are asynchronous - the callback code does not run immediately, it runs some time in the future when you actually get the data.
The easiest way to chain multiple dependent async queries is to put each query into its own function, and call it from the dependent query's callback. In your case, you could have multiple callbacks running at once, so as each one completes you can check for it to be done and check for them all to be done by comparing the size of the list with the number of queries launched.
For example:
private ArrayList<String> userList = new ArrayList<>();
private int numUsers = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// other setup stuff
startInitialQuery();
}
private void startInitialQuery() {
// make your initial query
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userList.clear();
numUsers = 0; // dataSnapshot.getChildren().size();
// If the size() call above works, use that, otherwise
// you can count the number of children this way.
for(DataSnapshot snap : dataSnapshot.getChildren()) {
++numUsers;
}
for(DataSnapshot snap : dataSnapshot.getChildren()) {
String userId = snap.getKey();
readUser(userId);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
}
private void readUser(String userId) {
// make userQuery using "userId" input
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String username = dataSnapshot.getValue().toString();
userList.add(username);
checkLoaded();
}
else {
--numUsers;
checkLoaded();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
--numUsers;
checkLoaded();
}
});
}
private void checkLoaded() {
if( userList.size() == numUsers ) {
// All done getting users! Show a toast, update a view, etc...
}
}
Alternately, if you switch to using Kotlin and coroutines you can write this as a pretty simple linear suspend function where you can actually make the different tasks wait.
A cleaner, but more invasive change, would be to move this all to a ViewModel that contains LiveData of each of these steps. As data is received, you post it to the LiveData and the UI can observe that and react accordingly (e.g update views, trigger the next call, etc).
Update
Here is an example showing how to do this with a ViewModel and LiveData
public class MainViewModel extends ViewModel {
private final MutableLiveData<List<String>> users = new MutableLiveData<>();
LiveData<List<String>> getUsers() {
return users;
}
private final ArrayList<String> userList = new ArrayList<>();
void startFetchingData() {
// build query
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userList.clear();
for(DataSnapshot snap : dataSnapshot.getChildren()) {
String userId = snap.getKey();
readUser(userId);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
}
private void readUser(String userId) {
// build userQuery
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String username = dataSnapshot.getValue().toString();
userList.add(username);
users.postValue(userList);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
}
}
and in the activity you set an observer for the LiveData that is notified any time the data changes.
model = new ViewModelProvider(this).get(MainViewModel.class);
final Observer<List<String>> userObserver = userList -> {
// Update the UI, or call something else
// this will get called every time the list of users is
// updated in the ViewModel
System.out.println("TEST: got data " + userList);
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
model.getUsers().observe(this, userObserver);
model.startFetchingData();
This question already has an answer here:
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 3 years ago.
private Firebase_Database DbOnline;
ArrayList<ClassModel> clsList;
clsList = DbOnline.getClassesList();//return arraylist containing objects ...
//Implementation of getClassesList() in Firebase_Database CLASS..
public ArrayList<ClassModel> getClassesList(){//upto to this every thing execute but from here the //execution jumps to if(condition) line below...and I get null arraylist in return
FbDb.child("Classes").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren())
{
ClassModel classModel = ds.getValue(ClassModel.class);
classModels.add(classModel);
Log.i("Tag", "Msg");
}
Log.i("Tag", String.valueOf(classModels.size()));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (classModels==null){
Log.i("TAG","Null NO DATA IN DATABASE");
}
return classModels;
}
Operation to firebase is asynchronous. so you have to wait to get data. You can use LiveData and observe it to get updated content. Check below:
private MutableLiveData<ArrayList<ClassModel>> mutableClassModels = new MutableLiveData<>();
private ArrayList<ClassModel> classModels = new ArrayList<>();
public MutableLiveData<ArrayList<ClassModel>> getClassesList(){//upto to this every thing execute but from here the //execution jumps to if(condition) line below...and I get null arraylist in return
FbDb.child("Classes").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren())
{
ClassModel classModel = ds.getValue(ClassModel.class);
classModels.add(classModel);
Log.i("Tag", "Msg");
}
mutableClassModels.postValue(classModels);
Log.i("Tag", String.valueOf(classModels.size()));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return mutableClassModels;
}
And then observe it like below:
DbOnline.getClassesList().observe(this, new Observer<ArrayList<ClassModel>>() {
#Override
public void onChanged(ArrayList<ClassModel> classModels) {
// Do your operation here
}
});
Update:
Update your adapter like below:
//Initialize it, as it causing NullPointerException
ArrayList<ClassModel> clsList = new ArrayList<>();
public Adapter(Context context, String name) {
...
DbOnline=new Firebase_Database();
if (fragName.equals(listForClasses)) {
DbOnline.getClassesList().observe((LifecycleOwner) context, new Observer<ArrayList<ClassModel>>() {
#Override
public void onChanged(ArrayList<ClassModel> classModels) {
clsList =classModels;
clsList.size();
//Notify to refresh the items
notifyDataSetChanged();
}
});
} else {
sList = null;//DbOffline.getStudentsList("");
}
}
Not sure why, but with the code I have, I cannot seem to get the value of 'isOnline':
dolRef = DatabaseReference dolRef = FirebaseDatabase.getInstance().getReference("DriversOnline");
dolRef = dolRef.child("iosDriver");
dolRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String driverid = ds.getKey();
// get value of 'isOnline'
dolRef = dolRef.child(driverid);
Log.e(TAG, "dolRef: " + dolRef);
dolRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dss : dataSnapshot.getChildren()) {
String online = dss.child("isOnline").getValue(String.class);
Log.e(TAG, "Online: " + online);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Below is a part of my firebase db:
"DriversOnline" : {
"iosDriver" : {
"BruEGfToc8axIWJk1o01fxcwd8I2" : { // driverId
"isOnline" : "true",
"latitude" : 45.276,
"longitude" : -66.064
}
}
}
Any idea why I can't get the value of 'isOnline' other than null ?
I think you're nesting your listeners one level deeper than needed.
DatabaseReference iosRef = FirebaseDatabase.getInstance().getReference("DriversOnline/iosDriver");
iosRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot driverSnapshot: dataSnapshot.getChildren()) {
String driverid = driverSnapshot.getKey();
DataSnapshot isOnlineSnapshot = driverSnapshot.child("isOnline");
System.out.println(isOnlineSnapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Some things to note:
Reassigning one generically named dolRef variable 4 times in a block of code like this is a code-smell. It makes it much harder to follow what's going on, and to check if the variable points to the right location. Give each of them a name that clearly indicates what they point to, as I've done above.
There is no need to attach a second listener, as the value of isOnline is right in the driverSnapshot. You can just request the child snapshot with the right name, and then the value from that.
Don't ignore error, as that hides potential problems. At the very least throw them, as I've done above.
driverid = FirebaseDatabase.getInstance().getReference("driver");//If there is another driver table, the path must be two layers.
driverid.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Driver driver = dataSnapshot.getValue(Driver.class);//class model
dolRef = FirebaseDatabase.getInstance().getReference("DriversOnline/iosDriver").child(driver.getDriverID);
dolRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DriversOnline driversOnline= dataSnapshot.getValue(DriversOnline .class);//class model
log.d("driverid","isOnline :"+driversOnline.getisOnline)
//display -> isOnline : true
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I'm making an app and I need to match data continuously in the activity. I'm using firebase for the database and I'm getting problem of getting my query right. I want to match the data in child(uid) to other data in different child(uid), in this case I'm still testing with only the date.
EDIT: I need to match the child of uid1 (for this case, the date) to ALL EXISTING dates available in the "Schedules". My bad.. the previous question stated was wrong where i said "matching the uid1 data to uid2 data"
Here is my code. I think my conditions aren't correct.
mInstance.getReference("Schedules").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Schedule schedule = dataSnapshot.child(uid).getValue(Schedule.class);
for(DataSnapshot data: dataSnapshot.getChildren()) {
if (dataSnapshot.child(uid).child("date").exists() && dataSnapshot.child(uid).child("date").getChildrenCount()>= 2) {
test.setText("Found Match for " + schedule.date + "," + schedule.sport + ", and " + schedule.location);
} else {
test.setText(schedule.date + schedule.sport + schedule.location);
}
}
}
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
Looking at your database cant a child("date") with children count greater than two.
If i may ask why are doing this?
There are two different approach to solve this problem
Get a list<> of all schedules from database and simply compare uid
or
If you already know the uid of the data you are looking for, get the data from database
More on firebase query
private Query queryGetSchedule;
private Query queryAllSchedule;
private ValueEventListener schedulesListener;
private ValueEventListener allSchedulesListener;
private FirebaseDatabase;
//Inside onCreate or class your are using
this.context = context; //pass in context
this.app = FirebaseApp.initializeApp(context);
this.id = myid;
if(firebaseDatabase == null) firebaseDatabase = FirebaseDatabase.getInstance();
queryGetSchedule = firebaseDatabase.getReference("Schedules").Child("key");
queryAllSchedule = firebaseDatabase.getReference().child("Schedules");
/**
* This will get you a single schedule
*/
public void getSingleSchedules()
{
if(schedulesListener == null)
{
schedulesListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
// MainActivity.userBook = snapshot.getValue(UserBook.class);
Schedule schedule = snapshot.getValue(Schedule.class);
callback.onUserCallback(userBook);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
};
}
queryGetSchedule.addListenerForSingleValueEvent(schedulesListener);
}
/**
*This will get you all your schedules in a list so you can easily compare
* Let assume you are passing in schedule of interest into this method
*/
public void getAllSchedulesListener(Schedule scheduleOfInterest) {
if(allSchedulesListener == null) {
allSchedulesListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
//Use this for list of objects passing in the type
GenericTypeIndicator<List<Schedule>> schedulesList =
new GenericTypeIndicator<List<Schedule>>() {
};
if(dataSnapshot.exists()) {
List<Schedule> mySchedulesList = dataSnapshot.getValue(schedulesList);
//after you get this full list of schedule you can compare with date as a string
for(Schedule schedule: mySchedulesList)
{
if(scheduleOfInterest.date.equals(schedule.date)
{
//found it
//do whatever here
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
};
}
queryAllSchedule.addListenerForSingleValueEvent(allSchedulesListener);
}
To solve this, simply use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidOneRef = rootRef.child("Schedules").child(uidOne);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String dateOne = ds.child("date").getValue(String.class);
Query uidTwoRef = rootRef.child("Schedules").orderByChild("date").equalTo(dateOne);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String dateTwo = ds.child("date").getValue(String.class);
Schedule schedule = dataSnapshot.getValue(Schedule.class);
if(dateOne.equals(dateTwo)) {
test.setText("Found Match for " + schedule.date + "," + schedule.sport + ", and " + schedule.location);
} else {
test.setText(schedule.date + schedule.sport + schedule.location);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidTwoRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidOneRef.addListenerForSingleValueEvent(valueEventListener);
In which uidOne and uidTwo are the id of the users you want to check. I highly recommend you to store the data as a timestamp and not as a String, as it is explained here.
So guys, I had the database: Event and User.
When some user has interest in some event clicking the button, this will add a child in eventHasInterest with the user in Event database, and in the database User will add the event that has interest. It's already working, but I need to put a counter to show, how many people has interest, and it's not working, only add once. I need one click, +1, another click -1 on.
btn_interest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseEvent.child(getKeyEvent()).addListenerForSingleValueEvent( //get the event by key
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Event event = dataSnapshot.getValue(Event.class);
user = FirebaseAuth.getInstance().getCurrentUser(); //get the user logged in
if(user != null) {
databaseUser.orderByChild("userEmail").equalTo(user.getEmail()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
final User user = userSnapshot.getValue(User.class); // user data logged in
databaseUser.orderByChild("userHasInterest").equalTo(event.getEventId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
databaseUser.child(user.getUserId()).child("userHasInterest").child(event.getEventId()).setValue(event.getEventId());
databaseEvent.child(event.getEventId()).child("eventAmount").setValue(dataSnapshot.getChildrenCount()+1);
} else {
//event already exists
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseEvent.orderByChild("eventHasInterest").equalTo(user.getUserId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
databaseEvent.child(event.getEventId()).child("eventHasInterest").child(user.getUserId()).setValue(user.getUserId());
} else{
//user already exist
}
}
My firebase:
dataSnapshot.getChildrenCount() does not return the int value of eventAmount, it returns the number of children that eventAmount has. In your case, eventAmount will always return 0 since there is no children of eventAmount. I suggest that instead of using getChildrenCount, get the value of the dataSnapshot, and parse that value into an int. After that, increment that value by 1, and store that value instead.
databaseEvent.child(event.getEventId()).child("eventAmount").setValue(Integer.parseInt(dataSnapshot.getValue().toString()) + 1);
EDIT: As suggested by Frank, storing the value using a transaction is recommended to help avoid concurrent updates. I used this post, as well as the post Frank linked to help write the code.
public void updateCount(DatabaseReference database){
database.runTransaction(new Handler() {
#Override
public Result doTransaction(MutableData mutableData) {
//Currently no value in eventAmount
if(mutableData.getValue() == null){
mutableData.setValue(1);
}
else{
mutableData.setValue(Integer.parseInt(mutableData.getValue().toString()) + 1);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
//Probably log the error here.
}
});
}
So in your "userHasInterest" onDataChange method, call my method above like this.
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(!dataSnapshot.exists()) {
databaseUser.child(user.getUserId()).child("userHasInterest").child(event.getEventId()).setValue(event.getEventId());
updateCount(databaseEvent.child(event.getEventId()).child("eventAmount")); //New line here
} else {
//event already exists
}
}