I'm trying to add a data to Firebase and Increment its Child.

I'm getting it done until the value/Id is three. Then when I inserted a data for the fourth time, it replaces one of the data and can't increment more than three. So, what could be the problem?

This is my Java Code

public class EnterInkhawmProg extends AppCompatActivity {


    EditText tv1, tv2, tv3, tv4, tv5, tv6, tv7;
    Button btn;
    Program program;
    long maxid = 0;

    DatabaseReference ref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inkhawp_prog);

        tv1 = findViewById(R.id.edittext_date);
        tv2 = findViewById(R.id.edittext_chairman);
        tv3 = findViewById(R.id.edittext_tantu);
        tv4 = findViewById(R.id.edittext_thilpek);
        tv5 = findViewById(R.id.edittext_biblechhiar);
        tv6 = findViewById(R.id.edittext_thusawitu);
        tv7 = findViewById(R.id.edittext_hunhmandan);

        program = new Program();

        ref = FirebaseDatabase.getInstance().getReference().child("Inkhawm");

        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    maxid = (dataSnapshot.getChildrenCount());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {


            }
        });

        btn = findViewById(R.id.sub_btn);

        btn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                program.setDate(tv1.getText().toString().trim());
                program.setChairman(tv2.getText().toString().trim());
                program.setTantu(tv3.getText().toString().trim());
                program.setThilpek(tv4.getText().toString().trim());
                program.setBiblechhiarrual(tv5.getText().toString().trim());
                program.setThusawitu(tv6.getText().toString().trim());
                program.setHunhmandan(tv7.getText().toString().trim());

                ref.child(String.valueOf(maxid+1)).setValue(program);
                Toast.makeText(EnterInkhawmProg.this, "Success", Toast.LENGTH_SHORT).show();
                        tv1.setText("");
                        tv2.setText("");
                        tv3.setText("");
                        tv4.setText("");
                        tv5.setText("");
                        tv6.setText("");
                        tv7.setText("");
            }
}

1 Answers

0
Ahmed El-Nakib On Best Solutions

just replace this line

                ref.child(String.valueOf(maxid+1)).setValue(program);

with

                ref.child(String.valueOf(maxid+1)).push().setValue(program);