Reputation: 33
In Firebase, I list my data by auto increment. However, when i any data is deleted, i can't new data added. Updating is being made on the last added data. I need a solution for this.
Firebase
My Source:
public class MainActivity extends AppCompatActivity {
EditText name_et;
Button button_save;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
long autoincrementid =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name_et = findViewById(R.id.aaaa);
button_save = findViewById(R.id.btnsave);
databaseReference = firebaseDatabase.getInstance().getReference().child("Data");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists());
autoincrementid=(snapshot.getChildrenCount());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
button_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String a = name_et.getText().toString();
databaseReference.child(String.valueOf(autoincrementid+1)).setValue(a);
Toast.makeText(MainActivity.this, "+++++", Toast.LENGTH_SHORT).show();
}
});
}
}
Upvotes: 0
Views: 208
Reputation: 600090
Right now you use the count of children to determine what the next number is. That works well if all sequential indexes are occupied, but (as you found) not when you delete one of more indexes in there.
The proper solution in that case depends on what you want to happen. I know of these general use-cases:
Possible code for a solution that finds the first available id:
databaseReference = firebaseDatabase.getInstance().getReference().child("Data");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
int autoincrementid = 0;
do {
autoincrementid++;
} while (snapshot.hasChild(""+autoincrementid));
snapshot.child(""+autoincrementid).setValue("New value");
})(
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
A few notes on this code:
Upvotes: 1