简体   繁体   中英

Saving multiple gps locations to same firebase real-time database

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 az 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;
    }
}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM