Home > Net >  Saving multiple gps locations to same firebase real-time database
Saving multiple gps locations to same firebase real-time database

Time:03-04

I have successfully stored longitudinal and latitudinal coordinates to the Firebase Realtime Database when a button is pressed. The current database overwrites the coordinates if the phone's location changes. However, I would like to append the new coordinates to the database without overwriting the previously saved ones.

I have tried to pass one of the coordinate strings as the child however the database only accepts a-z letters. There are five separate buttons that each log the user's mood and the location at that mood.

btnGreat = (ImageButton) view.findViewById(R.id.btnGreat);
btnGreat.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        rootNode = FirebaseDatabase.getInstance();
        reference =  rootNode.getReference("Location");
        String latitude = Latitude.getText().toString();
        String longitude = Longitude.getText().toString();

        Coordinates coordinates = new Coordinates(latitude, longitude);
        reference.child("great").setValue(coordinates);
    }
});

coordinates class:

public class Coordinates {
    String latitude, longitude;

    public Coordinates() {
    }

    public Coordinates(String latitude, String longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }
}

CodePudding user response:

Since you are using the setValue() method, it means that each time you call this method it overrides the data at the existing location. If you want to have different values for the coordinates under the great node, then you should consider using the push() method like this:

reference.child("great").push().setValue(coordinates);

This will create a database structure that looks like this:

Firebase-root
  |
  --- Location
        |
        --- great
             |
             --- $pushedId
             |      |
             |      --- latitude: 1.11
             |      |
             |      --- longitude: 2.22
             |
             --- $pushedId
                    |
                    --- latitude: 3.33
                    |
                    --- longitude: 4.44

Then you can simply read the data:

  • Related