简体   繁体   中英

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. For this case, I have 2 activities: DepartGermany and DepartGermany2.

In the first activity a new Trip node is created, containing 3 attributes: city, zip, street.

In the second activity I want the user to add a phone number and a name to the same "Trip" 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. 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);

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