Search code examples
androidgoogle-mapsfirebase-realtime-databaseoncreate

Why does my Google Map keep creating new map instances after Firebase onDataChange() method triggered?


I am having trouble updating the Google Map on my MapsActivity when reading in a coordinate from Firebase. I want to have it so that whenever a database change is detected (this point's latitude or longitude changes), the marker that is on the map changes to match the new latitude and longitude that was found in the database.

However, while doing this, I came to realize that whenever the database updated and onDataChange() was called, onCreate() was being called thereafter, leading to another instance of a Map to be created. For this reason, when I attempt to go back on my phone (back button), I stumble previous Maps (before the database change).

Also, the map opens up even when the app is not opened. The database query is being called in onMapReady(). The code executes as follows:

Pre-database change:

onCreate()

onMapReady()

  • onDataChange() -- inside onMapReady()

and then:

Post-database change:

onDataChange()

onCreate()

onMapReady()

  • onDataChange() -- inside onMapReady()

Does anyone know why this is happening?


edit: if this is important to note, I have tried moving the database queries to onCreate() with no avail-- I moved it after:

mapFragment.getMapAsync(this);

edit : code block for onCreate()

 @Override
protected void onCreate(Bundle savedInstanceState) {
    Paper.init(this);
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_maps);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.

        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    StartPinActivity.databaseChildren.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot user : dataSnapshot.getChildren()) {
                Child child = user.getValue(Child.class);
                assert child != null;
                if (child.getPhoneNumber().equals(ProfileAdapter.clickedProfile.getPhoneNumber())) {
                    if (childMarker == null) {
                        LatLng childLocation = new LatLng(child.getLatestLat(), child.getLatestLong());
                        MarkerOptions childMarkerOptions = new MarkerOptions().position(childLocation).title("Child's location");
                        childMarker = mMap.addMarker(childMarkerOptions);
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(childMarkerOptions.getPosition()));
                        Toast.makeText(MapsActivity.this, "A new child location has been received.", Toast.LENGTH_SHORT).show();

                        break;

                    }
                    else {
                        LatLng childLocation = new LatLng(child.getLatestLat(), child.getLatestLong());
                        MarkerOptions childMarkerOptions = new MarkerOptions().position(childLocation).title("Child's location");
                        childMarker.setPosition(childMarkerOptions.getPosition());
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(childMarkerOptions.getPosition()));
                        Toast.makeText(MapsActivity.this, "A new child location has been received.", Toast.LENGTH_SHORT).show();

                        break;
                    }
                }
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    Button finalizeButton = findViewById(R.id.finalize);
    finalizeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            StartPinActivity.databaseParents.child(Paper.book().read(CURRENT_ID).toString()).child("geofences").setValue(geofenceList);
        }
    });

}

Solution

  • Thank you all for your responses!

    I finally fixed my program; it was actually a simple error that wasn't even in the activity I was looking at this entire time. When onDataChange is called in one activity, it's called in all of its instances in all other activities as well. I accidentally started my MapsActivity onDataChange() in my previous activity, so every time the data changed in my database, onCreate() was called!