How to get value from Firebase to recycleView - java

this is a picture of firebase datathis is the image of log which i am getting in logcat
mDatabase=FirebaseDatabase.getInstance();
mRef=mDatabase.getReference("items").child("0").child("snippet");
mChildEventListner = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
for (DataSnapshot Snapshot : dataSnapshot.getChildren()) {
CategoriesModelClass user = dataSnapshot.getValue(CategoriesModelClass.class);
Log.d("kkk", "" + user);
title_description.add(user);
}
categoriesRecycleView.notifyDataSetChanged();
}
This is my code from activitymain and I don't know should I fire query for title and description or it it will fetch it from the for loop?
this is the code of my model class
public class CategoriesModelClass {
String title,description;
public CategoriesModelClass(){
}
public CategoriesModelClass(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
}
and i am try to set this data in my recycle view i need only title and description

To get the values of description and title, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference snippetRef = rootRef.child("items").child("0").child("snippet");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
CategoriesModelClass user = dataSnapshot.getValue(CategoriesModelClass.class);
Log.d("kkk", "" + user.getTitle());
//Get the values out of the user object
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
snippetRef.addListenerForSingleValueEvent(valueEventListener);
See, there is no need to loop over the snippet node, and this because we need to get the data according to type of object that is stored.
If there will be more than one items in the 0 node, then please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference zeroRef = rootRef.child("items").child("0");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
CategoriesModelClass user = ds.getValue(CategoriesModelClass.class);
Log.d("kkk", "" + user.getTitle());
}
//Get the values out of the user object
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
zero.addListenerForSingleValueEvent(valueEventListener);

Related

Why does DataSnapshot return null?

I want to read data from Firebase but Log.d("Uservalue", ""+value); return null for me, what should I do?
MainActivity.java:
FirebaseUser user = mAuth.getCurrentUser();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("USERS").child(user.getUid());
User user1 = new User(user.getEmail(), user.getDisplayName(), user.getUid(), user.getPhotoUrl().toString());
/* write to firebase database */
myRef.setValue(user1);
/*read*/
myRef.child(user.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User value = dataSnapshot.getValue(User.class);
Toast.makeText(MainActivity.this, "User", Toast.LENGTH_SHORT).show();
Log.d("Uservalue", ""+value);
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
User.java:
public class User{
private String email;
private String id;
private String imgurl;
private String name;
public User(){
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String email, String name, String id, String imgurl) {
this.email = email;
this.id = id;
this.imgurl = imgurl;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return this.name;
}
public void setname(String username) {
this.name = username;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
And my firebase data:
And Logcat return null
020-06-03 17:53:12.810 8720-8720/com.example.chatapp D/Uservalue: null
Can anyone help me? Thank you.
And then
I want to ask a question, why User value = dataSnapshot.getValue(User.class); know the name in firebase = name in User, the email in firebase = email in User ......, so that I use value.getName() can get my name's data.
The following call to setValue():
myRef.setValue(user1);
It's an asynchronous operation. So if you want to use (read) that data, you should wait until the write operation is completed. So please check the following lines of code:
uidRef.setValue(user1).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("USERS").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Log.d("TAG", user.getName());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
}
}
});
Your myRef is already on USERS/$uid node. So change your ValueEventListener to
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
User value =
dataSnapshot.getValue(User.class);
Toast.makeText(MainActivity.this, "User",
Toast.LENGTH_SHORT).show();
Log.d("Uservalue", ""+value);
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
Edit: Or change your Database Reference to
myRef=FirebaseDatabase().getInstance(). getReference("USERS");
myRef.child(user.getUid).setValue(your data);
myRef.child(user.getUid).addValueEventListener(//the rest are same
);
Your myRef is already pointing to your user node
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("USERS").child(user.getUid());
You are trying listen to another branch of your user node by mentioning uid
myRef.child(user.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User value = dataSnapshot.getValue(User.class);
Toast.makeText(MainActivity.this, "User", Toast.LENGTH_SHORT).show();
Log.d("Uservalue", ""+value);
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
Change this code to this
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User value = dataSnapshot.getValue(User.class);
Toast.makeText(MainActivity.this, "User", Toast.LENGTH_SHORT).show();
Log.d("Uservalue", ""+value);
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});

DatabaseException: can't convert object of java.Lang.String to type

I'm trying to retrieve data from my Firebase Realtime Database but encountering this issue.
I'm suspecting I got this error due to my path in DatabaseReference. I tried different paths but none seemed to work.
Here's my database (The generated texts are userID)
My class that stores the data structure
public class ERDataStructure {
private String temperature;
private String humidity;
public ERDataStructure() {
}
public ERDataStructure(String temperature, String humidity) {
this.temperature = temperature;
this.humidity = humidity;
}
public String getTemperature(){
return temperature;
}
public void setTemperature(String temperature){
this.temperature = temperature;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
}
My ReadingScreen.java (MainActivity)
import ...
public class ReadingScreen extends AppCompatActivity {
//Firebase Initialization
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private FirebaseDatabase mFirebaseDatabase;
private static final String TAG = "ReadingScreen";
ERDataStructure mData;
private TextView textViewTemperatureNumber, textViewHumidityNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading_screen);
//Find Views
textViewHumidityNumber = (TextView) findViewById(R.id.humidity_number);
textViewTemperatureNumber = (TextView) findViewById(R.id.temperature_number);
// Initiate Firebase
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
// Non-working Reference, but code works
//myRef = mFirebaseDatabase.getReference();
//myRef = mFirebaseDatabase.getReference().child(userID);
//Crashing Reference
myRef = mFirebaseDatabase.getReference().child(userID).child("ERDataStructure");
//myRef = mFirebaseDatabase.getReference("ERDataStructure");
//
retrieveData();
}
public void gotoMainMenu (View view)
{
Intent intent = new Intent(ReadingScreen.this, MainMenu.class);
startActivity(intent);
}
private void retrieveData(){
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
textViewTemperatureNumber.setText("" +ds.getTemperature());
textViewHumidityNumber.setText(""+ds.getHumidity());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
textViewTemperatureNumber.setText("" +ds.getTemperature());
textViewHumidityNumber.setText(""+ds.getHumidity());
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<ERDataStructure> arraylist = new ArrayList<ERDataStructure>();
if (dataSnapshot != null && dataSnapshot.getValue() != null){
//FirebaseUser user = mAuth.getCurrentUser();
//String userID = user.getUid();
for (DataSnapshot a : dataSnapshot.getChildren()){
ERDataStructure dataStructure = new ERDataStructure();
dataStructure.setTemperature(a.getValue(ERDataStructure.class).getTemperature());
dataStructure.setHumidity(a.getValue(ERDataStructure.class).getHumidity());
arraylist.add(dataStructure);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
The error was recorded in
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
Edit: After adding another level to my database, it manages to run
You need to use ValueEventListener instead of ChildEventListener, so change it to this:
myRef = mFirebaseDatabase.getReference().child(userID).child("ERDataStructure");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In this case you use ValueEventListener, because when you use childEventListener you are basically looping inside this snapshot and returning the value of humidity as type String. It is like looping over dataSnapshot.getChildren() in the valueventlistener.

How to retrieve the sibling node's value in firebase?

What I'm trying to do is to return the value of the key named class of the node named m1 with a sibling named name
Here's what my database looked like
Here's what my code looked like
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Medicines");
final Query userQuery = rootRef.orderByChild("name").equalTo(textView.getText().toString());
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
txt1.setText(myParentNode);
DatabaseReference childRef = FirebaseDatabase.getInstance().getReference().child(myParentNode);
childRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String class_ = dataSnapshot.getValue().toString(); txt2.setText(class_);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
However it just gave me error T.T
Try this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Medicines");
final Query userQuery = rootRef.orderByChild("name").equalTo(textView.getText().toString());
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
String class=datas.child("class").getValue().toString();
String name=datas.child("name").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
the datasnasphot is medicines then the query is orderByChild("name").equalTo(textView.getText().toString()); equal to the value that is in the textView.
String keys=datas.getKey(); this will get you the key can be m1 or m2 or m3 depending on the text that you retrieve from the textview.
Then the other two will retrieve the name and the class from the database that are under a specific key.
Try this:
Create a class called Medicine(If you don't already have one) and make it have two String variables name and class and create a constructor, getter and setter methods then use this method:
public String getClassOfMedicineById(String id){
final String medicineClass = "";
FirebaseDatabase.getInstance().getReference("medicine-handbook").child("Medicines")
.child(id)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Medicine medicine = dataSnapshot.getValue(Medicine.class);
medicineClass = medicine.get_class();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return medicineClass;
}
And then call it like:
getClassOfMedicineById("m1");
Oh and don't call your class getter method getClass(). I think there's a method in the Object class so it might interfere or something.

Android - Firebase database child node

I have a Firebase databse structure like this :
the firebase database structure
Now I want to access the items in the node "comingSoonPages" to a model class. How can i get the reference to these different user specified items in that node?
The database reference :
mUpcomingDatabaseReference = mFirebaseDatabase.getReference().child("comingSoonPages").child("blrKoramangala")
now the listener to the reference is as :
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapShot : dataSnapshot.getChildren()){
Log.e("snap" , String.valueOf(snapShot));
try{
UpcomingProperty property = snapShot.getValue(UpcomingProperty.class);
Log.e("name" , String.valueOf(property.getName()));
}catch (Exception ex){
ex.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mUpcomingDatabaseReference.addValueEventListener(mValueEventListener);
when i try to log the names in each of the nodes , i get NPE and the value is null.
The model class in which i am mapping is :
public class UpcomingProperty implements Serializable {
//private Amenities amenities;
private List<String> amenities;
private Coordinates coordinates;
private Image image;
private String link;
private String location;
private String name;
private Text text;
private List<String> sortParameter;
private EarlyBird earlyBird;
public UpcomingProperty(){}
public List<String> getAmenities() {
return amenities;
}
public void setAmenities(List<String> amenities) {
this.amenities = amenities;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Text getText() {
return text;
}
public void setText(Text text) {
this.text = text;
}
public List<String> getSortParameter() {
return sortParameter;
}
public void setSortParameter(List<String> sortParameter) {
this.sortParameter = sortParameter;
}
public EarlyBird getEarlyBird() {
return earlyBird;
}
public void setEarlyBird(EarlyBird earlyBird) {
this.earlyBird = earlyBird;
}
}
Thanks.
the extended firebase node :
extended node values
To get that data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference comingSoonPagesRef = rootRef.child("comingSoonPages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
comingSoonPagesRef.addListenerForSingleValueEvent(eventListener);
The out will be the only the names. But you can get also all the other values in the same way.
If you want to use the model class, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference comingSoonPagesRef = rootRef.child("comingSoonPages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
UpcomingProperty upcomingProperty = ds.getValue(UpcomingProperty.class);
Log.d("TAG", upcomingProperty.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
comingSoonPagesRef.addListenerForSingleValueEvent(eventListener);
You'll have the same output.
Assuming that comingSoonPages holds a list of item, You need to add a ChildEventListener on the comingSoonPages reference if you want to access all the child nodes of that.
DatabaseReference upcomingItemsRef = mFirebaseDatabase.getReference().child("comingSoonPages");
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
if(dataSnapshot.exists()) {
// Handle each individual node like blrKoramangala, cyberHub here.
String key = dataSnapshot.getKey();
// Get the UpcomingProperty object here.
UpcomingProperty property = dataSnapshot.getValue(UpcomingProperty.class);
Log.d(TAG, "property.getName():" + property.getName();
}
}
// Other methods of ChildEventListener go here
};
upcomingItemsRef.addChildEventListener(childEventListener);
You can read more about working with lists of data here.
However, if that's not a list, here's what you're doing wrong:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Don't do this. It will get the children of blrKoramangala and
// those won't be of UpcomingProperty type.
// Remove and replace with dataSnapshot.exists()
for (DataSnapshot snapShot : dataSnapshot.getChildren()){
...
}
}

how get value from Firebase

I am new in android and I want to get userIDS from Firebase Database, I've tried by using this but it returns null.
By using this code
Value of Constants.ARG_CHAT_GROUP_ROOMS=Groups and Constants.NEW_NODE=newGroup
private void getMYuid() {
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child(Constants.ARG_CHAT_GROUP_ROOMS).child(Constants.NEW_NODE)
.child(senderUid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Toast.makeText(ActivityChatView.this, "not exist", Toast.LENGTH_SHORT).show();
Log.e("151","ACV"+dataSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("139","ACV"+senderUid);
}
Database Structure is this
if you want the first one under 15052169227329_myGroupName_Hell By Anne: Your problem is that you forgot the node before "Constants.NEW_NODE"
private void getMYuid() {
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child(Constants.ARG_CHAT_GROUP_ROOMS).child("15052169227329_myGroupName_Hell By Anne").child(Constants.NEW_NODE)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Toast.makeText(ActivityChatView.this, "not exist", Toast.LENGTH_SHORT).show();
Log.e("151","ACV"+dataSnapshot);
}
// You can cast this object later but it seems that that is a string and not an array
Object yourRequiredObject = dataSnapshot.child("usersIDS").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("139","ACV"+senderUid);
}
As i see, it's not an array it's a String. To get the userIDS, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child(Constants.ARG_CHAT_GROUP_ROOMS).child(senderUid).child(Constants.NEW_NODE);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String usersIDS = dataSnapshot.child("usersIDS").getValue(String.class);
Log.d("TAG", usersIDS);
//Here you can split the usersIDS String by , (comma)
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
In which senderUid is the missing child. This child can have the value like 1505217176288_myGroupName_1 or other coresponding group names.

Categories

Resources