简体   繁体   English

如何向 Firebase 实时数据库中的现有数据添加新属性?

[英]How to add new attributes to existing data in Firebase Realtime Database?

I'm creating an app in Android Studio, which will allow a registered users to book trips.我正在 Android Studio 中创建一个应用程序,它将允许注册用户预订旅行。 For this case, I have 2 activities: DepartGermany and DepartGermany2.对于这种情况,我有 2 个活动:DepartGermany 和 DepartGermany2。

In the first activity a new Trip node is created, containing 3 attributes: city, zip, street.在第一个活动中,创建了一个新的 Trip 节点,包含 3 个属性:city、zip、street。

In the second activity I want the user to add a phone number and a name to the same "Trip" ID.在第二个活动中,我希望用户将电话号码和姓名添加到同一个“旅行”ID。 How would you recommend me to do this?你会怎么推荐我做这件事?

Below is the code for the first activity, which is working fine.下面是第一个活动的代码,它工作正常。 Thank you in advance!先感谢您!

public class DepartGermany extends AppCompatActivity {

    Spinner spinnerCity;

    EditText editTextZIP;
    EditText editTextStreet;

    Button buttonAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_depart_germany);

        spinnerCity = (Spinner) findViewById(R.id.selectCountries);
        editTextZIP = (EditText) findViewById(R.id.editTextZIP);
        editTextStreet = (EditText) findViewById(R.id.editTextStreet);
        buttonAdd = (Button) findViewById(R.id.addButton);


        String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();

        databaseTrips = FirebaseDatabase.getInstance().getReference("TripsAll").child(currentUser);

        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addTrip();
            }
        });
    }

    private void addTrip(){
        String city = spinnerCity.getSelectedItem().toString().trim();
        String zip = editTextZIP.getText().toString().trim();
        String street = editTextStreet.getText().toString().trim();

    String id = databaseTrips.push().getKey();

        Trips trip = new Trips(
                city,
                zip,
                street
        );

    databaseTrips.child(id).setValue(trip);

        Intent intent = new Intent(DepartRomania.this, DepartGermany2.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
}

You'll need to know the key/ID of the trip that you want to add data to.您需要知道要向其添加数据的行程的密钥/ID。 Once you do that, updating the node with the new properties is a matter of:一旦你这样做了,用新属性更新节点就是一个问题:

HashMap<String, Object> values = new HashMap<>();
values.put("phonenumber", "+1-800-555-6789");
values.put("name", "Name of the trip");
databaseTrips.child(id).updateChildren(values);

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

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