Looping through string fetched from FirebaseDatabase. How to? - android

I'm fetching some strings in firebase which are all saved under tag 'imageUID' and using this imageUIDs to show images.
Here's how I'm fetching it:
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
imageUID = newRequest.get("imageUID");
}
#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) {
}
});
This is how I'm using the above fetched imageUID to show images:
private void doSomethingWithPicasso(String imageUIDh, ImageView target){
Picasso.with(getBaseContext())
.load(imageUIDh)
.error(R.drawable.ic_warning_black_24dp)
.into(target, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
Toast.makeText(getBaseContext(), "Error occurred while loading images. Please retry.", Toast.LENGTH_SHORT).show();
}
});
}
I want to show each every image shown using imagesUIDs fetched from database in my app, but what is happening is only the last imageUID is getting used to show images and not all of them.
I was thinking about looping through this string and using each string one by one to show images, but I don't know how to do that! Is there any better way to achieve this?

you may get some help from this try this
firebase.child("key").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot innerDataSanpShot : dataSnapshot.getChildren()) {
//DataSnapshot of inner Childerns
String username = innerDataSnapShot.child("username").getValue().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});

Related

Delete a child from firebase android?

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(com.google.android.gms.maps.model.Marker marker) {
// Toast.makeText(Map.this, marker.getPosition()+"", Toast.LENGTH_SHORT).show();
Query query = databaseReferenceMarkers.orderByChild("lat").equalTo(marker.getPosition().latitude);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Toast.makeText(Map.this, "test", Toast.LENGTH_SHORT).show();
dataSnapshot.getRef().removeValue();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return true;
}
});
Why am I not able to delete the marker?
onChildRemoved() -- no response.
The problem is that you're adding a value change listener, so onChildRemoved() will only be called once you remove the child, but you're removing it in the callback function.
Try it like this:
Query query = databaseReferenceMarkers.orderByChild("lat").equalTo(marker.getPosition().latitude);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) { child.getRef().removeValue(); }
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
The query returns a collection of datasnapshots where there is a match. Then you'd need to iterate over them deleting every one of them.

How to display Firebase Parents in Listview

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) {
}
});

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) {
}
});

Using Android Loader while retrieving data from Firebase

I am retrieving data from Firebase and use this data to present some information. Since retrieving data takes time I put a CountDownTimer to make the app wait but it is not a nice solution and it does not look good. I found that Android Loader can do this job but I could not make it work. Can anyone solve this?
Here is the code I use to get data from Firebase.
infoReference.addChildEventListener(new ChildEventListener() { //inforeference is DatabaseReference
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
try {
Info info = postSnapshot.getValue(Info.class);
infoList.add(info); //Just an arraylist
}catch(Exception e){
}
}
}
#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 use
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doSomething();
}
},2000);
right after retrieving data from firebase,yet not a very good idea. looking for solution too.

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