Reputation: 25
I'm working in Android Studio on an app that uses Firebase for signing in and store data to its realtime database. I'm using the default firebase database rules, so only authenticated users can write/read in the database.
I've an activity (AddMarker) that saves two editText values and one LatLong value (this one from another activity) to the database. The code is actually working and i can see data stored in it in this way: DB structure
The problem is that everytime i save (in AddMarker Activity), the previous data linked to that id, gets replaced by the new one.
Instead i would like to store in the DB multiple values with the same id like this for example:
DB structure 2
This is my code
public class AddMarker extends AppCompatActivity implements View.OnClickListener {
//Save flag
public static boolean isSaved;
//Database
private DatabaseReference databaseReference;
FirebaseAuth firebaseAuth;
private FirebaseAuth mAuth;
//UI
private EditText tipo, marca;
private Button saveMarker;
public LatLng ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_marker);
//DB
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
//Initialize views
tipo = (EditText) findViewById(R.id.type);
marca = (EditText) findViewById(R.id.specInfo);
saveMarker = (Button) findViewById(R.id.save_btn);
//Initialize isSaved
isSaved = false;
//Set button listener
saveMarker.setOnClickListener(this);
//get Position
ll = getIntent().getParcelableExtra("POSITION");
}
private MarkerOptions saveMarkerInfo(){
String tipo_str = tipo.getText().toString().trim();
String marca_str = marca.getText().toString().trim();
LatLng pos = ll;
MarkerInfo markerInfo = new MarkerInfo(tipo_str,marca_str, pos);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
MarkerOptions marker = new MarkerOptions()
.position(ll)
.anchor(0.0f, 1.0f)
.title("prova")
//Add data to DB
databaseReference.child(user.getUid()).setValue(markerInfo);
Toast.makeText(this,"infos saved",Toast.LENGTH_LONG).show();
finish();
return marker;
}
@Override
public void onClick(View v) {
if(v == saveMarker){
isSaved = true;
MarkerOptions mo=saveMarkerInfo();
MainActivity.mMap.addMarker(mo);
}
}
}
Upvotes: 1
Views: 9015
Reputation: 785
you cannot create two nodes with same Id instead you can create a nested structure inside each userId. and setValues accordingly like this.
databaseReference.child(user.getUid()).push().setValue(markerInfo);
this will create childs under singleUserId with your multiple data
for more you can refer this
Upvotes: 5