0

Stop retrieve data from Firebase after its loaded.

This is my code:

databaseReference.child("SHARE").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            information spacecraft = ds.getValue(information.class);
            spacecrafts.add(spacecraft);
        }
        adapter adapterView= new adapter(MainActivity.this, spacecrafts);
        gridView.setAdapter(adapterView);
    }
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
mohamed
  • 1
  • 3
  • Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – Clijsters Jan 03 '18 at 20:47
  • Add single value listener if you want to load your data once and not in real time. Hope it helps – Rahul Singh Chandrabhan Jan 04 '18 at 04:37

2 Answers2

1

Use addListenerForSingleValueEvent instead of addValueEventListener if you want to read the whole data once.

Or if you want to get update from onDataChange, you can remove the listner,

 ValueEventListener eventListener = databaseReference.child("SHARE").addValueEventListener(new   ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {

            information spacecraft = ds.getValue(information.class);
            spacecrafts.add(spacecraft);

        }
        adapter adapterView= new adapter(MainActivity.this, spacecrafts);
        gridView.setAdapter(adapterView);
    }

To remove the listener,

databaseReference.child("SHARE").removeEventListener(eventListener);
Priya
  • 672
  • 1
  • 5
  • 21
1

Use addListenerForSingleValueEvent()

databaseReference.child("SHARE").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                information spacecraft = ds.getValue(information.class);
                spacecrafts.add(spacecraft);

            }
            adapter adapterView= new adapter(MainActivity.this, spacecrafts);
            gridView.setAdapter(adapterView);
        }

have a look on this answer https://stackoverflow.com/a/41579337/5868103

Benjith Mathew
  • 1,211
  • 1
  • 11
  • 23