Can't get data from Firebase Database on Android - java

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

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 a single data from Firebase Realtime Database

I'm new to firebase and I wanted to store a high score and retrieve it from Firebase Realtime database. The storage is working as intended , but I couldn't find a tutorial to retrieve the stored data. The official documentation is a bit confusing for me. Kindly help me out.
public class result extends AppCompatActivity {
TextView fscore,highs; Button pagain; String scor; int hs,scrcheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
fscore=(TextView)findViewById(R.id.finalscore);
highs=(TextView)findViewById(R.id.his);
pagain=(Button)findViewById(R.id.pagain);
scor=getIntent().getStringExtra("score");
fscore.setText(scor);
// need code here to retrieve the existing highscore value from firebase and assign it to highs textview.
//code to update highscore
scrcheck=Integer.parseInt(scor);
if(scrcheck>hs)
{
hs=scrcheck;
FirebaseDatabase.getInstance().getReference().child("highscore").setValue(hs);
}
highs.setText(Integer.toString(hs));
}
This is my Firebase database
.
Thanks in advance.
Based on the documentation on getting values:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("highscore").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("highscore: " + dataSnapshot.getValue(Long.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Not getting all results for RecyclerView from firebase

My app has two categories of users shop owner and buyers.
When shop owner adds a shop I use his UID and then pushkey to add a shop like this:
In the Image "83yV" and "FmNu" are the shop owners and they add 2 and 1 shop respectively.
Now for buyers, I want to show the whole list of shops in a Recycler View.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_shops_avtivity);
shopsDB = FirebaseDatabase.getInstance().getReference().child("shops");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Shop,ShopViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Shop, ShopViewHolder>(
Shop.class,
R.layout.shop_single_layout,
ShopViewHolder.class,
shopsDB)
}
The problem is when I point my Firebase Recycler Adapter to shopDB, it returns two empty cardView like this:
When I point it to specific child like
shopsDB = FirebaseDatabase.getInstance().getReference().child("shops").child("83yV24a3AmP15XubhPGApvlU7GE2");
It returns shops add by "83yV".
How can I get the shops added by other owners also? Preferably without altering current DB or creating one DB with all shops in it within on child.
To achieve this, you need to use getChildren() method twice, once to get all the users and second to get all the shops.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference shopsRef = rootRef.child("shops");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
for(DataSnapshot dSnapshot : ds.getChildren()) {
String name = dSnapshot.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
shopsRef.addListenerForSingleValueEvent(eventListener);
Using this code, you'll be able to display all shop names to the buyers.

Android studio debug does actions that simple run doesn't

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?

Categories