Getting data from firebase in array in Android - android

I am new to Firebase. I have following data in firebase:
Inside EventPlayer I have array of data for key eventID. I want to get all objects for a eventID in an Array.
My code:
final String eventId=intent.getStringExtra("EventID");
mref.child("EventPlayer").child(eventId).orderByChild("eventID").equalTo(eventId);
// Attach a listener to read the data at our posts reference
mref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
EventRequest post = child.getValue(EventRequest.class);
if(post != null){
System.out.println(post);
arrPlayers.add(post);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
The post has no value and it is an empty class.
Edit
Code for creating arrraylist:
arrPlayers = new ArrayList<EventRequest>();

Try this code. The only change is in the first few lines, with the postQuery variable.
final String eventId=intent.getStringExtra("EventID");
Query postQuery = mref.child("EventPlayer").child(eventId).orderByChild("eventID").equalTo(eventId);
// Attach a listener to read the data at our posts reference
postQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
EventRequest post = child.getValue(EventRequest.class);
if(post != null){
System.out.println(post);
arrPlayers.add(post);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Your second line of code creates a Query object, but you never assign it to anything. Assigning it to a new variable and then adding the ValueEventListener to that new variable should get you to your data.

To get all those event ids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference eventIdRef = rootRef.child("EventPlayer").child(eventId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String eventID = ds.child("eventID").getValue(String.class);
list.add(eventID);
Log.d("TAG", eventID);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
eventIdRef.addListenerForSingleValueEvent(eventListener);

Related

Retrieving data from particular nodes firebase Database

I am developing an android application and now I am stuck in retrieving data from particular nodes like I want to retrieve only one value from each nodes. The database structure shows below.
How can I retrieve the second unique id that created by Firebase database?
First create a POJO class to get the values you want, it should be writen the same way as you have them in Firebase.
public class AppointmentsPojo {
private String appointmentStuts;
public AppointmentsPojo(){
}
public String getAppointmentStuts() {
return appointmentStuts;
}
public void setAppointmentStuts(String appointmentStuts) {
this.appointmentStuts = appointmentStuts;
}
}
Then just loop inside Appointments to get each appointmentStuts
mDatabase.child("Appointments").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Looping inside Appointments to get each appointmentsStuts
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
AppointmentsPojo ap = snapshot.getValue(AppointmentsPojo.class);
//Getting each appointmentStuts
String appointmentStuts = ap.getAppointmentStuts();
//To get each father of those appointments
String key = snapshot.getKey();
Log.e("Data: " , "" + appointmentStuts );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Where mDatabase is
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
To get the value of appointmentStuts only from the first object, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Appointments").child(PostKey).limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String appointmentStuts = ds.child("appointmentStuts").getValue(String.class);
Log.d(TAG, appointmentStuts);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);

Can't convert object of type java.lang.String to type User

databaseQuestion = FirebaseDatabase.getInstance().getReference("users").child(KrgDOh_GnwpIons_r9Q);
databaseQuestion.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// System.out.println("VAL"+dataSnapshot.getValue());
//clearing the previous artist list
usersQuestions.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//iterating through all the nodes
//getting artist
System.out.println("VAL"+postSnapshot.getValue());
User user = postSnapshot.getValue(User.class);
//adding artist to the list
usersQuestions.add(user);
}
//creating adapter
QuestionUserList userQuestionsAdapter = new QuestionUserList(getActivity(), usersQuestions);
//attaching adapter to the listview
questionsList.setAdapter(userQuestionsAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am facing the following error
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type
I want to fetch the data and display it in Listview. Please help out.
Assuming that users node is the direct child of Firebase root, to get those values, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String question = ds.child("question").getValue(String.class);
String userId = ds.child("userId").getValue(String.class);
Log.d("TAG", address + " / " + question + " / " + userId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
Having those values, you can create a new object of your class as add it to questionsList list. Also don't forget to declare that list inside the onDataChange() method, otherwise it will be null.
Hope it hels.

I'm not able to receive data from my firebase database

I'm a rookie regarding firebase and android.
After reading for a while I have raise a question regarding my code:
I'm not able to read information from my firebase database.
here's my code:
#Override
protected void onStart() {
super.onStart();
mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference referenceArtista = mDatabase.child("artists");
final List<Pintura> pinturaList = new ArrayList<Pintura>();
referenceArtista.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot artistaSnapshot: dataSnapshot.getChildren()) {
Artista artista = artistaSnapshot.getValue(Artista.class);
pinturaList.addAll(artista.getPinturaList());
}
RecyclerView recyclerViewPintura = (RecyclerView)findViewById(R.id.recyclerView);
recyclerViewPintura.setHasFixedSize(true);
recyclerViewPintura.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL,false));
AdapterPintura adapterPintura = new AdapterPintura(getBaseContext(),pinturaList);
recyclerViewPintura.setAdapter(adapterPintura);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
My database structure looks something like this:
Database
I've been debugging and I'm seeing that the list at the end of the foreach cycle, returns null. (hence I'm greeted with a NullPointerException and the app crashes)
Thanks in advance :)
You are getting null because List<Pintura> pinturaList = new ArrayList<Pintura>(); is declared outside the onDataChange() method. You need to declare and use it inside that method and outside the for loop, otherwise is null, due the asynchronous behaviour of the method, which is called before you even add those Artista class objects to the list.
To solve this, please use this code:
referenceArtista.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<Pintura> pinturaList = new ArrayList<Pintura>();
for (DataSnapshot artistaSnapshot: dataSnapshot.getChildren()) {
Artista artista = artistaSnapshot.getValue(Artista.class);
pinturaList.addAll(artista.getPinturaList());
}
Log.d("TAG", artista); // Here is not null
RecyclerView recyclerViewPintura = (RecyclerView)findViewById(R.id.recyclerView);
recyclerViewPintura.setHasFixedSize(true);
recyclerViewPintura.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL,false));
AdapterPintura adapterPintura = new AdapterPintura(getBaseContext(),pinturaList);
recyclerViewPintura.setAdapter(adapterPintura);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to use that list outside onDataChange() method, please see my answer from this post.
Can you initailize your recycler vioew in onCreate method and once you get the data from the firebase just update the adapter
pinturaList = new ArrayList<Pintura>();
dataSnapshot.getChildrenCount();
//List<User> list= new ArrayList<User>();
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Artista artista = artistaSnapshot.getValue(Artista.class);
pinturaList .add(user);
}
adapter.update(pinturaList );
Instead of addListenerForSingleValueEvent use ValueEventlistener then use forEach loop because single return single or null value if you have more than one
Try this
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("YOUR TABLE NAME").getRef();
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
Log.v("dataSnapshot.getValue()", "" + dataSnapshot.getValue());
for (DataSnapshot dss : dataSnapshot.getChildren()) {
HashMap<String, String> map = (HashMap<String, String>) dss.getValue();
//get your values
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Displaying the database nodes from Firebase in a list in Android

A simple question:
Referring to my database image, I want to get the values of the children of node "user" in a list in an Activity, i.e. values "a" and "m" should be displayed in the list.
What should I use and how?
Please try this code:
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("user");
yourRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> usersList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = (String) ds.getKey();
usersList.add(userName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This is the way in which you'll have in your list, a, m ans so on.
Hope it helps.
You can get the info from the docs here
List<User> allUsers = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("user");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allUsers.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
allUsers.add(userSnapshot.getValue(User.class));
}
yourRecyclerViewAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Users failed, log a message
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
// ...
}
});

Get last node in Firebase database Android

I want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot
The last node
Try this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
}
});
Hope this helps!
This might work:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User val", child.child("message").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: Handle errors.
}
});
I prefer to write and retrieve data through objects.
MyObject is POJO.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
MyObject myObject = data.getValue(MyObject.class);
Log.i(TAG, data.getKey() + " = " + myObject.toString());
}
}
console.log('last messages', messages[messages.length-1]);

Categories

Resources