Skip to content Skip to sidebar Skip to footer

How To Invoke Valueeventlistener Of Firebase Programatically In Android

student_edit.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { noof_placed=0; placpercen

Solution 1:

student_edit.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {

       // do your task
   }

   @Override
   public void onCancelled(FirebaseError firebaseError) {

   }
});

Call this method whenever you requires. It will not run everytime when data is inserted in firebase.

Solution 2:

To trigger your listener, you can either write to the database student_edit location, or isolate the listener and then call that. I assume that writing to the database is self-explanatory. To isolate the listener, you could add a member field to your class:

ValueEventListener studentListener;

Then initialize that field and set the listener based on it:

studentListener = newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) 
    {
        noof_placed=0;
        placpercent=0.0;
        enrolled=0;

        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) 
        {

            StudentDetail std = 
            postSnapshot.getValue(StudentDetail.class);
            std.setRollno(postSnapshot.getKey());
            studentlist.add(std);
            enrolled++;


            if (!std.getPlacementcompany().toString().trim().equals("0")) 
            {

                noof_placed++;

            }
        }
        placpercent=(noof_placed / total_students) * 100;
        start_progressbar(noof_placed,placpercent);
   }
    @OverridepublicvoidonCancelled(DatabaseError databaseError) 
    {
    }
});
student_edit.addValueEventListener(studentListener);

And then you can call it anywhere with:

studentListener.onDataChange(YOUR_SNAPSHOT);

Of course the problem becomes that you then need to keep the snapshot around.

Post a Comment for "How To Invoke Valueeventlistener Of Firebase Programatically In Android"