Issue
In short, when I click on the marker it must register the user id of the user who clicked on "Partecipanti". The problem is that if the first user is saved regularly when a second user clicks, this overwrites the first one. How can I solve it?
@Override
public void onInfoWindowClick(@NonNull Marker marker) {
LatLng latLon = marker.getPosition();
for(Incontro incontro : Incontri) {
if (latLon.equals(incontro.getLatlng())) {
if(){
Toast.makeText(Cercaincontro.this, "You are already attending this event", Toast.LENGTH_SHORT).show();
}
else {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Incontro").child(incontro.getIncontroidId());
HashMap<String, Object> hashMap1 = new HashMap<>();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
hashMap1.put("userid", firebaseUser.getUid());
reference.child("Partecipanti").child(uid).setValue(true);
}
}
}
}
Solution
While @AliasCartellano's solution to pushing data into the Realtime Database will work, please note a pushed ID it's not the best option to identify a user. Why? Because every time you call push(), another unique key is generated.
Since I see in your screenshot that you store some long IDs, other than the pushed IDs, the ones that start with -
(minus), I assume you're using authentication. That being said, a more recommended way to store user data would be like this:
Firebase-root
|
--- users
|
--- $uid
|
--- //user data
And to add data to such a structure, you should use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
reference.child("Partecipanti").child(uid).setValue(hashMap1);
This means, that each user will write data under a separate location since each UID is unique. So in this way, you cannot overwrite the data.
Edit:
Firebase-root
|
--- users
|
--- $uid: true
|
--- $uid: true
And in code:
reference.child("Partecipanti").child(uid).setValue(true);
Edit2:
To be able to write an object that looks like this, please use the following lines code:
Map<String, Object> data = new HashMap<>();
data.put("addressorganizz", "messina");
data.put("cittaorg", "messin");
//As as much data as you need.
reference.child("Partecipanti").child(uid).setValue(data);
Edit3:
//Data
Map<String, Object> data = new HashMap<>();
data.put("addressorganizz", "messina");
data.put("cittaorg", "messin");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference reference = FirebaseDatabase.getInstance()
.getReference("Incontro")
.child(incontro.getIncontroidId())
.child(uid);
reference.setValue(data);
Answered By - Alex Mamo
Answer Checked By - Candace Johnson (JavaFixing Volunteer)