简体   繁体   English

将多个 gps 位置保存到同一个 firebase 实时数据库

[英]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.当按下一个按钮时,我已经成功地将经度和纬度坐标存储到 Firebase 实时数据库中。 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.但是,我想将 append 新坐标写入数据库,而不覆盖以前保存的坐标。

I have tried to pass one of the coordinate strings as the child however the database only accepts az letters.我试图将其中一个坐标字符串作为孩子传递,但是数据库只接受 az 字母。 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:坐标 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.由于您使用的是setValue()方法,这意味着每次调用此方法时它都会覆盖现有位置的数据。 If you want to have different values for the coordinates under the great node, then you should consider using the push() method like this:如果你想在great节点下的坐标有不同的值,那么你应该考虑像这样使用push()方法:

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:然后你可以简单地读取数据:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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