Android studio debug does actions that simple run doesn't - java

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?

Related

Firebase Realtime database read not working (Android Java)

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();
}

Android: Notify on specific value change in Firebase real-time database

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.

Retrieve data from FireBase database in android, java by searchin with an ID

I tried to implement a code in java to retrieve data from database( firebase) by searching with an ID and show it in the form.
In here i have already saved some data and now when i type the id, it need to show the data of the id in this same form.
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchID = txtid.getText().toString().trim();
DatabaseReference readRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dref = readRef.child("Student");
Query query = dref.orderByChild("id").equalTo(searchID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
txtID.setText((dataSnapshot.child("id").getValue().toString()));
txtName.setText((dataSnapshot.child("name").getValue().toString()));
txtAdd.setText((dataSnapshot.child("address").getValue().toString()));
txtConNo.setText((dataSnapshot.child("conNo").getValue().toString()));
}
else
Toast.makeText(getApplicationContext(),"No Source to Display",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
This is the java code i implemented to do that. But when i run the program and give the correct id in database it is always showing as "No source to display"( There are data in my database and save function is working properly)
I am a beginner in android studio and firebase. Please modify the above code and tell me how can i search by ID.
Thankyou.
Try the following:
if(dataSnapshot.exists()){
for(DataSnapshot ds : dataSnapshot.getChildren()){
txtID.setText((ds.child("id").getValue().toString()));
txtName.setText((ds.child("name").getValue().toString()));
txtAdd.setText((ds.child("address").getValue().toString()));
txtConNo.setText((ds.child("conNo").getValue().toString()));
}
}
Your reference is at node Student therefore you need to loop and then use ds to access the attributes. Also, don't forget to check for errors inside onCancelled:
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}

Android Studio debug does not log Firestore Database Reading

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!

Can't get data from Firebase Database on Android

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

Categories