Reading data from firebase real time database into text view - java

I want to read from the firebase real time database and set retrieved data in a textview, here is what I have tried so far.
private DatabaseReference buckybarnz;
.........
buckybarnz = FirebaseDatabase.getInstance().getReference().child(userID).child("chel_sea");
ValueEventListener eventListener = buckybarnz.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
if (dataSnapshot1 != null) {
DRive dRive = dataSnapshot1.getValue(DRive.class);
if (dRive != null) {
String receipt = dRive.getExt_ref().trim();
String text = dRive.getTxt_Ref().trim();
chalwe.setText(text);
johns.setText(receipt);
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Nothing is working, even when there's data in the database nothing happens to the textviews.
Please help, what is the best way to solve this problem, even a solution using the string class method would be beneficial. Below is a view of my database this is a view of my database, BSQ.... being the userID]1

I have accessed the database in a different way compared to you :
Firebase.setAndroidContext(this);
Firebase reference1 = new Firebase("https://project-id.firebaseio.com/messages/"); //replace project-id by your project-id
reference1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("reference4: data snapshot key"+dataSnapshot.getKey()+"");
//your code
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Hope this helps

First of all you don't have to write the for loop, and this should be your edited code in the onChildAdded() method of my code :
if (dataSnapshot != null) {
DRive dRive = dataSnapshot.getValue(DRive.class);
if (dRive != null) {
String receipt = dRive.getExt_ref().trim();
String text = dRive.getTxt_Ref().trim();
chalwe.setText(text);
johns.setText(receipt);
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
}
Hope this works

Related

How to pass firebase data from one activity to another?

I want to pass data from one activity to another, first I download it from Firebase Realtime Database and then pass it to another activity and how to use it in it.
my data like this.(image from the internet)
cam_firebase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NotNull DataSnapshot dataSnapshot, String s) {
// long count = dataSnapshot.getChildrenCount();
double longt = dataSnapshot.child("longt").getValue(Double.class);
double lat = dataSnapshot.child("lat").getValue(Double.class);
String type = dataSnapshot.child("type").getValue(String.class);
List<Model> list = new ArrayList<>();
list.add(new Model());
list.get(0).setLat(lat);
list.get(0).setLongt(longt);
cameras_info.onCallback();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});
Assuming that pXGb...lGE2 is the UID of the logged-in user, to be able to read the data that corresponds to your schema, then please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("ProgressReportss").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot ds : snapshot.getChildren()) {
String content = ds.child("content").getValue(String.class);
String timestamp = ds.child("timestamp").getValue(String.class);
String title = ds.child("title").getValue(String.class);
Log.d("TAG", content + "/" + timestamp + "/" + title);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Test 2/30-11-2018/Test 2
Test 3/30-11-2018/Test 3
Test 4/30-11-2018/Test 4
That's how you read it. If you need to send the data to another activity, inside the onComplete() use the logic in the following answer:
How to pass an object from one activity to another on Android

how to get specific nodes under unique keys in firebase realtime database android

I am trying to get data from nested nodes under unique keys. Each key is identical. It's difficult for me to deal with such problem help please.
I have tried ChildEventListener on database reference but not succeeded.
here is the code i am using to retreive data
InfoFragment.java
auth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference("Seller").getRef().child("ImpInfo");
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postDataSnapshot : dataSnapshot.getChildren()) {
ShopSellerInfo shopSellerInfo = postDataSnapshot.getValue(ShopSellerInfo.class);
mShopSellerInfo.add(shopSellerInfo);
}
mNearBySellerAdapter = new NearBySellerAdapter(getContext(), mShopSellerInfo);
mRecyclerView.setAdapter(mNearBySellerAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return rootView;`
ShopSellerInfo.java
public ShopSellerInfo(String shopAddress, String shopPhoneNo, String
shopImageUrl, String shopName) {
this.shopAddress = shopAddress;
this.shopPhoneNo = shopPhoneNo;
this.shopImageUrl = shopImageUrl;
this.shopName = shopName;
}
public ShopSellerInfo() {
}
public String getShopAddress() {
return shopAddress;
}
public String getShopPhoneNo() {
return shopPhoneNo;
}
public String getShopImageUrl() {
return shopImageUrl;
}
public String getShopName() {
return shopName;
}
public void setUserAddress(String shopAddress) {
this.shopAddress = shopAddress;
}
public void setUserPhoneNo(String shopPhoneNo) {
this.shopPhoneNo = shopPhoneNo;
}
public void setImageUrl(String shopImageUrl) {
this.shopImageUrl = shopImageUrl;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
}
This is the structure of my Database
I have a specific node in each unique key the contain data. I want to retrieve that data form every child node and show on single activity.
You're not too far off, just a few mistakes. The following is closer to what you need:
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference("Seller");
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot sellerSnapshot : dataSnapshot.getChildren()) {
DataSnapshot impInfoSnapshot = sellerSnapshot.child("ImpInfo");
ShopSellerInfo shopSellerInfo = impInfoSnapshot.getValue(ShopSellerInfo.class);
mShopSellerInfo.add(shopSellerInfo);
mNearBySellerAdapter = new NearBySellerAdapter(getContext(), mShopSellerInfo);
mRecyclerView.setAdapter(mNearBySellerAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
Changes:
Removed the call to .getRef(), which is not needed and in general an anti-pattern.
Removed the call to .child("ImpInfo") from the DatabaseReference, since there is no /Seller/ImpInfo.
Added .child("ImpInfo") in the loop, since you want the ImpInfo child of each snapshot.
Raise an error if onCancelled triggers, since it's a bad practice to ignore errors.

Why am I receiving empty strings after receiving valid data from Firebase?

Using Firebase, I'm trying to display to the user people they have matched with. I already have valid data for testing this and I have already run tests with sample data to see if everything else works.
Now, when I use real data from Firebase, problems occur.
This is what I have for code:
public String username = "";
public String profileImage = "";
public String discussion = "";
private void FetchMatchInformation(final String key, final String choice) {
DatabaseReference matchDb = FirebaseDatabase.getInstance().getReference().child("answers").child(key);
matchDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String opposite = postSnapshot.getValue(String.class);
if(opposite.equals("agree") && choice.equals("disagree")) {
DatabaseReference found = FirebaseDatabase.getInstance().getReference().child("users").child(postSnapshot.getKey());
found.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals("username")) {
username = postSnapshot.getValue(String.class);
}
if(postSnapshot.getKey().equals("providerId")) {
String provider = postSnapshot.getValue(String.class);
if(provider.equals("google.com")) {
Uri photoUrl = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
String originalPieceOfUrl = "s96-c/photo.jpg";
String newPieceOfUrlToAdd = "s400-c/photo.jpg";
String photoPath = photoUrl.toString();
String newString = photoPath.replace(originalPieceOfUrl, newPieceOfUrlToAdd);
profileImage = newString;
} else if(provider.equals("facebook.com")) {
profileImage = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString() + "?type=large";
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
FirebaseDatabase.getInstance().getReference().child("debates").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals(key)) {
discussion = postSnapshot.getValue(String.class);
break;
}
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
MessagesObject objDisc = new MessagesObject(username, discussion, profileImage);
resultsMessages.add(objDisc);
mMessagesAdapter.notifyDataSetChanged();
} else if(opposite.equals("disagree") && choice.equals("agree")) {
DatabaseReference found = FirebaseDatabase.getInstance().getReference().child("users").child(postSnapshot.getKey());
found.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals("username")) {
username = postSnapshot.getValue(String.class);
}
if(postSnapshot.getKey().equals("providerId")) {
String provider = postSnapshot.getValue(String.class);
if(provider.equals("google.com")) {
Uri photoUrl = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
String originalPieceOfUrl = "s96-c/photo.jpg";
String newPieceOfUrlToAdd = "s400-c/photo.jpg";
String photoPath = photoUrl.toString();
String newString = photoPath.replace(originalPieceOfUrl, newPieceOfUrlToAdd);
profileImage = newString;
} else if(provider.equals("facebook.com")) {
profileImage = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString() + "?type=large";
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
FirebaseDatabase.getInstance().getReference().child("debates").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals(key)) {
discussion = postSnapshot.getValue(String.class);
break;
}
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
MessagesObject objDisc = new MessagesObject(username, discussion, profileImage);
resultsMessages.add(objDisc);
mMessagesAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
So what's happening is I'm getting the user's username, their profile image, and figuring out the value, which I called discussion after determining the valid key. These values are all being accessed from different tree structures from the same real-time database.
Now, at the end of the if or else-if statement, I create and instantiate the MessagesObject by passing in the username, profile image, and discussion variables. I then add this object to the List<MessagesObject> called resultMessages. I then notify my custom adapter mMessagesAdapter that the data has changed.
Like I said, all the other pieces of code work perfectly fine. It's just when I pass username, discussion, and profileImage it always passes an empty string. I know this from using the debugger.
Why is that? It should not be doing that.

how to fetch data in range using timestamp - Firebase, Android, Real-time Database

I am using firebase real-time database to store and retrieve data but for some reason, I am unable to achieve what I want.
I want to get 20 records at a time on swipe refresh layout.
My data looks like:
Initially, I load 50 records:
chat.limitToLast(default_num_of_messages).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String user_id = map.get("user_id").toString();
String message = map.get("message").toString();
String timestamp = map.get("timestamp").toString();
Log.d("MAP", map.toString());
ChatMessage chat_message = new ChatMessage();
chat_message.setUser_id(user_id);
chat_message.setMessage(message);
chat_message.setTimestamp(Long.parseLong(timestamp));
Log.d("CHAT MSG", chat_message.toString());
if(Integer.parseInt(user_id) == Utils.getInstance().getLoggedInUser().getId()) {
addMessageBox(chat_message, 1);
}
else{
addMessageBox(chat_message, 2);
}
}
after these on refresh, I want to load 20 more. I am trying to do something like these. but it does not seem to return.
#Override
public void onRefresh() {
if(refresh_toggle) {
swipe_view.setRefreshing(true);
Log.d("CHAT", "REFRESHED!!!");
//reload new data
chat.orderByChild("timestamp").endAt(10).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String user_id = map.get("user_id").toString();
String message = map.get("message").toString();
String timestamp = map.get("timestamp").toString();
Log.d("CHATS", map.toString());
ChatMessage chat_message = new ChatMessage();
chat_message.setUser_id(user_id);
chat_message.setMessage(message);
chat_message.setTimestamp(Long.parseLong(timestamp));
swipe_view.setRefreshing(false);
if(Integer.parseInt(user_id) == Utils.getInstance().getLoggedInUser().getId()) {
addMessageBox(chat_message, 1);
}
else{
addMessageBox(chat_message, 2);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
}
As you can see I am trying to orderByChild "timestamp" and then tried different combination of startAt(), endAt() but nothing seem to work.
Try this:
int number_item_load = 10; //changed number if you want
public void loadMore(int offset, String theLastValue) {
// theLastValue: depend on your orderByChild() 's value
mDatabase = FirebaseDatabase.getInstance().getReference().child(Utils.FB_ROOT);
mEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (isAlreadyAttach()) {
// Get your item and callback to view and insert to listView
}
} ...
};
mDatabase.orderByChild("yourvalue").startAt(theLastValue).limitToFirst(number_item_load ).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// TODO Finished loaded number_item_load item
OnLoadedFinish(); //
mDatabase.removeEventListener(mEventListener); // Remove listener after load
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabase.orderByChild("yourvalue").startAt(theLastValue).limitToFirst(number_item_load ).addChildEventListener(mEventListener);
}
It worked perfectly in my case. Goodluck

How to retrieve specific list of data from firebase

I am new to firebase and nosql database
I am trying to retrieve some specific data from a Firebase. I have a node universities and that node has many unique identifier as node which has so more data into it. I want to retrieve name from each node.
Please have a look at this.
What I have tried so far: I tried using addChildEventListener but this only listens first child. I've debugged it and it was only showing the values of the first child of universities node.
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
List<University> university = new ArrayList<>();
Map<String, Object> td = (HashMap<String, Object>) dataSnapshot.getValue();
Log.d("TAG",dataSnapshot.getValue().toString());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have also tried addValueEventListener. This listens the whole node and return whole data, but I am unable to extract "name" for it since it contains unique identifiers.
Please guide me into the right directions.
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
University university = dataSnapshot.getValue(University.class);
List<University> universities = (List<University>) dataSnapshot.getValue(University.class);
*//*List<String> lst = new ArrayList<String>();
for(DataSnapshot dsp : dataSnapshot.getChildren()){
lst.add(dsp.getKey());
}
Log.d("TAG",lst.toString());*//*
Map<String, Object> td = (HashMap<String, Object>) dataSnapshot.getValue();
*//*List<Object> values = new ArrayList<Object>(td.values());
List<String> list=new ArrayList<String>();
for(int i=0; i<values.size(); i++){
list.add((String) values.get(i));
}*//*
Log.d("TAG", university.toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you using addValueEventListener for retrieve all university from Firebase
List<University> universityList = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
universityList.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
University university = postSnapshot.getValue(University.class);
universityList.add(university);
// here you can access to name property like university.name
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Or if you using addChildEventListener
List<University> universityList = new ArrayList<>();
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
University university = dataSnapshot.getValue(University.class);
universityList.add(university);
Log.i(TAG,"add university name = " + university.name);
...
}
...
}
Regarding Linh's answer about using the addEventListener method. You can use GenericTypeIndicator in order to directly create the list of objects you'll be needing. Here's a quick example:
List<University> universityList = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
GenericTypeIndicator<List<University>> t = new GenericTypeIndicator<List<University>>() {};
universityList = snapshot.getValue(t);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Hope this answer helps.
You can use equalTo() of Query in which you can pass your custom string to match with firebase database.
like this way you can create your Query and set listener with that
Query queryRef = myFirebaseRef.orderByChild("name").equalTo("some name");
refer this thread for more.
Here is nice example from firebase officials, refer that and you will get clear idea
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
User user = postSnapshot.getValue(User.class);
list.add(user);
}
}
class User
class User{
String name;
String phone;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getphone() {
return phone;
}
public void setphone(String phone) {
this.phone = phone;
}
List bind with class
List<User> list== new ArrayList <>();
100% it will work
I had the same problem .You can just change the access specifier i.e public to private in the Model class you problem will be solved

Categories