How to display Firebase Parents in Listview - android

The first 2 keys dont have child but others have them. I'm able to display the child elements when there is only one parent and I can display Admin/User details using data object model but how to display parent elements(Bright Kid Test & others) in Listview?
This is an image of Firebase Database:
Code:
listView = (ListView)findViewById(R.id.preschool_list);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list);
listView.setAdapter(adapter);
databaseReference = FirebaseDatabase.getInstance().getReference("Preschools");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.add(value);
adapter.notifyDataSetChanged();
}
#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) {
}
});
If there is only one child of preschools then it is displayed else no value is shown.

I've got the answer with datasnapshot.getChildren().
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dsp : dataSnapshot.getChildren())
{
list.add(String.valueOf(dsp.getKey()));
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

You want to display text Bright Kid LL, Bright Kid Mont, Bright Kid Test in list view, don't you? You can get them by getKey()
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot recipeSnapshot : dataSnapshot.getChildren()) {
String key = recipeSnapshot.getKey();
list.add(key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Problem in implementing ValueEventListeners

In the below code, I'm doing is what I am checking whether EventsRef dataSnapshot exists or not, if dataSnapshot exists = I am getting some values and storing it in a list and passing that list values to recyclerView method ,in that it displays those values, and my problem is if 2 users in online and both of them getting displayed those details , if user1 removes that reference from firebase database by deleting that event, user2 getting error and getting out of the application . I used child event listener as in the below code but it doesn't works as well . and if i use if else condtions inside the child event listener inside on child Added it also doesn't works , So please help me to solve this both issues .Thanks in advance.
EventsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
EventsRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s)
{
EventsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
for (DataSnapshot ds : dataSnapshot.getChildren())
{
String eventId = ds.child("Eid").getValue(String.class);
String gender = ds.child("Gender").getValue(String.class);
String serveCount = ds.child("Serve").getValue(String.class);
list.add(eventId);
list2.add(gender);
list3.add(serveCount);
}
if (list.size() != 0)
{
for (int i = 0; i < list.size(); i++)
{
RecyclerView(list.get(i), list2.get(i), list3.get(i));
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot)
{
Toast.makeText(WorkerMyEventActivity.this, "Event removed", Toast.LENGTH_SHORT).show();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else
{
progressDialog.dismiss();
TextView txt = (TextView) findViewById(R.id.txt);
txt.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

fail to retrieve data from firebase at datasnapshot object

this is my data and I want to retrieve it by using addValueEventListener but my app unfortunately stop
#Override
public void onStart() {
super.onStart();
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List.clear();
for(DataSnapshot dSnapshot :dataSnapshot.getChildren()){
List<String> td = (ArrayList<String>) dataSnapshot.getValue();
// data data1=dSnapshot.getValue(data.class);
List.add(data1);
}
DataList adapter =new DataList(Fragment1.this.getActivity(),List);
list.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
my app is stopped due to this line of code so tell me any alternative.
//**data data1=dSnapshot.getValue(data.class);
List.add(data1);)
Assuming that your db variable points out to the correct reference.
Instead of using ValueEventListener and looping through each child.
Use ChildEventListener and make sure that the DatabaseReference is pointing to the root where the child resides, so we can iterate through each POJO.
db.addChildEventListener(new ChildEventListener() {
public void onChildAdded(DataSnapshot dataSnapshot, String previousKey) {
list.add(dataSnapshot.getValue(YourModel.class)); // Change with your POJO
// Add to your list
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
public void onCancelled(DatabaseError er) { }});
If you want to retrieve Generics in Realtime Database use
Firebase's abstract class GenericTypeIndicator
GenericTypeIndicator<List<Message>> t = new GenericTypeIndicator<List<Message>>() {};
List<Message> messages = snapshot.getValue(t);
use this method
//-----------------// data inside kids----------
private void getDataFrom() {
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("kids");
mCustomerDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if (map.get("kid1ID") != null) {
customer_name = map.get("title").toString();
Log.i("kid1ID",String.valueOf(kid1ID));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

How to get User id from Firebase in android?

I have Done this:
adapter.getRef(currentPosition).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
adapterKey = dataSnapshot.getChildren().toString();
Log.i("adapterKey",adapterKey);
}
#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 want to retrieve the Id's generated by firebase in order to access the inner data to EndUsers node. How can I do that?
Try like this
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
//snapshot.getKey()
//snapshot.getValue()
}
DatabaseReference mDatabaseReference; //you must initialize it
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
Log.i(TAG, "the key is : " + child.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

ArrayList loses elements after onChildAdded (Android Studio & Firebase)

public void readUniversity(){
ChildEventListener uniListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//Log.d(LOG_TAG, dataSnapshot.getKey());
University uni = dataSnapshot.getValue(University.class);
universitieslist.add(uni); //Adding to an ArrayList of type University
//Log.d(LOG_TAG, universitieslist.size()+"is the size");
arrayofUniversities.add(uni.getName()); //Adding name of University to list
//Log.d(LOG_TAG, adapter.getCount() + " items");
//Log.d(LOG_TAG, arrayofUniversities.size()+" is the size");
adapter.notifyDataSetChanged();
}
#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) {
}
};
DatabaseReference uniReference = database.getReference("note-retrieve/Universities");
uniReference.addChildEventListener(uniListener);
}
The code is pretty much self explanatory. I am using arrayofUniversities a list to populate a spinner so I need an adapter. I am populating the spinner with the names of the Universities
I am storing the University Objects in universitieslist
The problem I have is when I leave the readUniversity() method I lose every element in universitieslist and arrayofUniversities even though my spinner is populated with these.
Its very strange as the list should have the objects stored.
Also, I have my adapter at the very top of the code in onCreate().
Try this way. Hope it will work .. :)
private Arrylist<University > universityList = new ArryList<>();
private Arrylist<String> universitysName = new ArryList<>();
mDatabase.getReference().child("path")
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
University mUniversity = dataSnapshot.getValue(University
.class);
universityList.add(mUniversity);
universitysName.add(mUniversity.getName);
}
}
#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) {
}
});
The problem seems to be with the adapter, if you can see the logs but the adapter is not updating, then is because the adapter is not being notified the data set has changed
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
University mUniversity = dataSnapshot.getValue(University
.class);
universityList.add(mUniversity);
universitysName.add(mUniversity.getName);
//UPDATE YOUR ADAPTER HERE
//spinnerAdapter.notifyDataSetChanged();
}
}
But I think the real problem is the origin of your current problem: You are getting each child. This is a way to do it, but for this case where you need all the data first and when that is ready show the spinner with the elements to the user, you should better get all the list elements in one query.
database.getReference("note-retrieve/Universities")..addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
University mUniversity = dataSnapshot.getValue(University
.class);
universityList.add(mUniversity);
universitysName.add(mUniversity.getName);
//ONCE THIS IS DONE, THEN PASS THE ARRAY TO THE ADAPTER
}
//The loop here is over, so you can set the adapter with the full list of data/universities
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to know number of items returned by query in Firebase

I have this query in my Firebase
mDataBase = FirebaseDatabase.getInstance().getReference("animals);
query = mDataBase.orderByChild("height").limitToLast(20);
query.addChildEventListener(new AnimalsEventListener());
My listener
private class AnimalsEventListener implements ChildEventListener{
private AnimalsEventListener(){
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Animals details = dataSnapshot.getValue(Animals.class);
}
#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) {
}
}
How can I get the size of all animals that matched the query before working on dataSnapShot? sometimes they can be less than 20;
It's not possible to know children count using ChildEventListener, use ValueEventListener instead.
public class AnimalsEventListener implements ValueEventListener {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() == 20) {
for (DataSnapshot dataSnapshotEntry : dataSnapshot.getChildren()) {
Animals details = dataSnapshotEntry.getValue(Animals.class);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
To attach this listener, use addValueEventListener() method
query.addValueEventListener(new AnimalsEventListener());
If you wanna use childEventListener i recommend u to use official FirebaseArray class.
To get the item count:
FirebaseArray mFirebaseArray = FirebaseArray(Query ref);
mFirebaseArray.getCount();

Categories

Resources