Reputation: 24
While I am currently in other activity if my database changes my app get me into the list view page which is as shown bellow:
I wanna know how to I stop refreshing the data while I am not currently looking at that activity Operating Code
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("new");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
// Object key = dataSnapshot.getValue();
if (dataSnapshot.hasChild(ch) ) {
Map<String ,Object> key = (Map<String, Object>) dataSnapshot.child(ch).getValue();
sname = (String) key.get("sname");
// Log.v("ABCD ", "Value is: " + key.get("sname"));
if(dataSnapshot.getValue() != null)
{
Intent intent = new Intent("com.example.sunny.new.Selectclass");
startActivity(intent);
finish();
}
} else{
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
builder1.setMessage("Check your Code");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.v("XYZ", "Failed to read value.", error.toException());
}
});
Upvotes: 0
Views: 1135
Reputation: 15543
At onPause
method of your activity, remove your event listener. And add it at onResume
method.
Detail:
Define your DatabaseReference
and ValueEventListener
as reachable variables because you are going to reference them at onPause
and onResume
methods:
ValueEventListener myValueEventListner;
DatabaseReference myRef;
// Below may be inside onCreate method:
myRef = FirebaseDatabase.getInstance().getReference().child("new");
myValueEventListner= new ValueEventListener() {
// your event listener logic here
};
Add & remove at onPause and onResume methods:
@Override
public void onResume() {
super.onResume();
myRef.addValueEventListener(myValueEventListner);
}
@Override
public void onPause() {
super.onPause();
myRef.removeEventListener(myValueEventListner);
}
Upvotes: 2