When running Android Studio Debug mode, it will not log my messages and will not add any rooms to my LinkedList when running the following code below. However, it runs perfectly when running it normally. I am running it through a connected samsung phone (not an emulator).
Does anyone know the reason why this happens?
final LinkedList<String> rooms = new LinkedList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference refDb = database.getReference();
refDb.child("Room").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "Starting search");
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
Log.d(TAG, "room: " + d.getKey());
System.out.println("room: " + d.getKey().toString());
rooms.add(d.getKey().toString());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, "->onCancelled");
System.out.println("room: cancelled");
}
});
As far as I could realize, your app is responding accordingly, but the Log.d(TAG, "room: " + d.getKey()); is not printing in your Logcat, right?
If yes, you just have to choose the device in your Logcat and your physical device must be connected to your PC via USB cable.
Good Luck!
Related
I am using realtime database in order to transfer information from a Windows computer to an Android phone. I am able to write data from the Windows PC to the database, but for some reason I am not able to read it off of the database to the Android. I am using Android studio Java. Here is the code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("users");
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
PCs.add(new PC(name));
}
for (int i = 0; i < PCs.size(); i++) {
PCs.get(i).setIp(dataSnapshot.child(PCs.get(i).getName()).child("ip").getValue(String.class));
PCs.get(i).setConnected(dataSnapshot.child(PCs.get(i).getName()).child("status").getValue(Boolean.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
It just doesn't go into the onDataChange method, but also doesn't go to the onCancelled method.
If it goes into neither of the callbacks, you may not have configured the connection to the database correctly. An easy way to fix that is to pass the database URL in the code, rather than depending on the google-services.json file:
DatabaseReference rootRef = FirebaseDatabase.getInstance("your database URL").getReference();
In general, you should never ignore possible errors, and implement onCancelled. At its minimum that should look like:
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
Following is screenshot of my Firebase realtime database. How can I notify a user whenever the item worker_id is changed?
I've tried the following code, but it notifies about each type of data change. I want notification specific to change in worker_id:
private void CheckDataChange(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("posts");
Query query = myRef.orderByChild("workType");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("Firebase","onDatachange");
for(DataSnapshot ds : dataSnapshot.getChildren()) {
try {
if(!ds.child("worker_id").getValue(String.class).equals("0")) {
Toast.makeText(MainActivity.this, "Request accepted", Toast.LENGTH_SHORT).show();
}
}catch (Exception ex){
Log.e("Firebase",ex.getMessage()+ex.getCause());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("Firebase", databaseError.getMessage());
}
};
query.addValueEventListener(valueEventListener);
}
There is nothing built into Firebase to raise an event only when the worker_id in your current structure changes.
The most common way to implement something like that would be to create a map mapping ds.getKey() to the value of worker_id when onDataChange is first called, and then comparing the value you get against that for any updates.
Whenever I updated the value 1st time, it works fine. But whenever I updated it again within a minute. The problem started, Firebase keeps updating, and as a result the apps crash. Can anyone help?
private void UpdatedStatus(String roomkey,String rents_not){
reference= FirebaseDatabase.getInstance().getReference("Room");
Query query = reference.orderByChild("Roomkey").equalTo(roomkey);
if (reference != null) {
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot1 : snapshot.getChildren())
{
String childPath=dataSnapshot1.getKey();
referenceUpdated = FirebaseDatabase
.getInstance().getReference("Room").child(childPath);
HashMap<String, Object> map = new HashMap<>();
map.put("Status", ""+rents_not);
referenceUpdated.updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
finish();
dialog.dismiss();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
In your current code, you do the following:
Set up a query for rooms with "Roomkey" == roomkey.
Attach a listener for updates on rooms that match the query
Upon getting results, set each matching room's status to rents_not
When you call UpdatedStatus("room1", "AVAILABLE"), everything works "fine" (the room "room1" is changed to AVAILABLE, then the room is changed to AVAILABLE again and finish.). Because you used addValueEventListener to listen for updates to the matching rooms, your code gets rerun when the data changes. This is why I said the status is changed twice.
Next, when you call UpdatedStatus("room1", "RENTED"), you experience the crash. After calling UpdatedStatus the second time, the status is changed to "RENTED", which fires both of the listeners from UpdatedStatus("room1", "AVAILABLE") and UpdatedStatus("room1", "RENTED"), constantly switching between "RENTED" and "AVAILABLE" forever.
You can fix this loop (and the double write) by using addSingleValueEventListener() instead. This will execute and read from the query only once.
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mRoomsRef = mDatabase.getReference("Room");
private void UpdatedStatus(String roomkey,String rents_not){
Query roomQuery = mRoomsRef.orderByChild("Roomkey").equalTo(roomkey);
roomQuery.addSingleValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot childSnapshot: snapshot.getChildren())
{
String childPath = childSnapshot.getKey();
DatabaseReference childRef = childSnapshot.getReference();
HashMap<String, Object> map = new HashMap<>();
map.put("Status", ""+rents_not);
childRef.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
finish();
dialog.dismiss();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.e(TAG, "Failed to get rooms for key: " + roomkey + "; " + error.getMessage());
}
});
}
}
As auspicious99 answered, since you update the same node that your query is listening for, your own call to updateChildren ends up triggering onDataChange again. And since you then update the node again, it triggers again, and again, and again... etc.
There are a few solutions for this:
Use addListenerForSingleValueEvent, which triggers only once and stops listener after that. This is the simplest change, as you can just change
query.addValueEventListener(new ValueEventListener() {
to
query.addListenerForSingleValueEvent(new ValueEventListener() {
You can also choose to detect whether the Status field is already set to rents_not and skip the update if it is. Inside the loop in onDataChange, you can do this with:
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot houseSnapshot: snapshot.getChildren()) {
DataSnapshot statusSnapshot = houseSnapshot.child("Status");
String status = statusSnapshot.getValue(String.class);
if (!rents_not.equals(status)) {
statusSnapshot.getReference().setValue(rents_not).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
finish();
dialog.dismiss();
}
});
}
}
You'll note that I've updated the code here a bit, since you can get the reference from the snapshot, and perform the update at the lower level.
These will both fix your current problem, so pick whichever works for the use-case. But since your new value of the Status node depends on its current value, consider using a transaction to update it, to eliminate the risk that two users will both post conflicting updates.
It looks like you may have an unintended loop, as inside your onDataChange, you are doing referenceUpdated.updateChildren(map), which changes data in your firebase database. This triggers onDataChange again, and so on.
You could break the circle by setting a Boolean/flag and checking it as needed.
So I have a set up where I want to get data from the Database on Firebase, I can get the URL back fine but I can't get data from it. When I try to debug it reads in query.addValueEventListener but after that it just goes straight to my list adapter. I don't know it's not getting the data. I have a similar set up on my node server which works perfectly fine, but won't work on Android for some reason
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
Query query = database.child("exercises");
Log.i("Database query", database.child("exercises").toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot exerciseSnapshot: dataSnapshot.getChildren())
{
List<ExerciseList> exercises = new ArrayList<ExerciseList>();
ExerciseList exerciseList = exerciseSnapshot.getValue(ExerciseList.class);
Log.i("description/name", exerciseList.getDescription() + " " + exerciseList.getName());
exercises.add(exerciseList);
adapter = new ExerciseLoadListAdapter(mActivity, exercises);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mListView.setAdapter(adapter);
its go to adapter directly because addValueEventListener() is Asynchronous listeners , its run in background !
Try this code , it may be help you !
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
//Query query = database.child("exercises");
//Log.i("Database query", database.child("exercises").toString());
database.child("exercises").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot exerciseSnapshot: dataSnapshot.getChildren())
{
List<ExerciseList> exercises = new ArrayList<ExerciseList>();
ExerciseList exerciseList = exerciseSnapshot.getValue(ExerciseList.class);
Log.i("description/name", exerciseList.getDescription() + " " + exerciseList.getName());
exercises.add(exerciseList);
}
adapter = new ExerciseLoadListAdapter(mActivity, exercises);
mListView.setAdapter(adapter)
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The Firebase do NOT get the data in the debug mode in real time. If you need some object from your firebase database you will need to get the object before. I face this problem a several times, thats why in some cases I use SQLite to store data from Firebase before i take any action. But, in a fragment you can not do that, you need the data in realtime. So you need to store the listener in a variable and use it after. Here in my Github page I have a fragment working fine.
ContatsFragment.java
[]'s
I am building an app using firebase realtime database. the app has a value eventlistener for reading data that should run at the first run of the activity and whenever the database's data change. This is my code:
this.mDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = this.mDatabase.getReference();
DatabaseReference userIntRef = databaseReference.child("users").child(user.getUid()).child("Page Number");
userIntRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentPage = dataSnapshot.getValue(long.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i("Database Error", databaseError.toException().toString());
}
});
For some reason, when I simply run the app, this block of code doesn't run when the activity is created, but when I debug the code, it runs as it should.
Does anyone know why, or how to solve it?