cah0k0n
cah0k0n

Reputation: 33

Firebase realtime database listing data with auto increment in Java

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 firebase realtime database

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

Answers (1)

Frank van Puffelen
Frank van Puffelen

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:

  • You want the list to behave like an array, which means that when you remove #3 in your JSON, the #4 and #5 actually get a new index. This will require you to change all other items when you remove one. For more on this see the answer I gave just now to another question: Firebase Remove with Javascript
  • You want to have an always increasing sequential index, typically referred to as a sequence or auto-increment values in relational databases. If you want this, you'll have to store the latest index that you handed out somewhere separate in the database and transactionally update that whenever you add an item to the list.
  • You want to put new items at the first available index, reusing the indexes of any deleted nodes. This seems to be your use-case, so we'll look at that further below.

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:

  • I didn't run it, so there may well be some minor errors in there. If you get any of those, please try to figure them out on your own and edit the answer to include the solution.
  • You probably should use a transaction here to ensure there are no conflicting updates. The logic of the loop will be the same though.

Upvotes: 1

Related Questions