0

This is the code I have written, but It is not working.

    EditText plant = (EditText)findViewById(R.id.plantname);
    String pn = plant.getText().toString();

    FirebaseAuth mAuth;
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();




    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myref  = database.getReference("Plants").child(String.valueOf(id+1));



    myref.child("Name").setValue(pn);
    myref.child("Latitude").setValue(lats);
    myref.child("Longitude").setValue(longs);

I want to add these three details many times, but with different indexes.

    myref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()){
                id = snapshot.getChildrenCount();
            }
        }

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

        }
    });
  • "It is not working" doesn't provide enough information so we can help. What exactly in this code doesn't work the way you expect? Besides that, stop ignoring errors. Use `Log.d(TAG, error.getMessage());`. Do you get something printed out in the logcat? – Alex Mamo Jul 10 '21 at 09:38
  • FirebaseDatabase database = FirebaseDatabase.getInstance(); myref = database.getReference("Plants").child(String.valueOf(id+1)); in this line, the index does not increase automatically. – Umar Farooq Jul 10 '21 at 10:19
  • Why would you do since Firebase [recommends against this practice](https://stackoverflow.com/questions/39519021/how-to-create-auto-incremented-key-in-firebase)? – Alex Mamo Jul 10 '21 at 10:21
  • I did not know that. can you suggest me any other solution for this scenario except using UIDs. – Umar Farooq Jul 10 '21 at 11:48
  • Try using [DatabaseReference#push()](https://firebase.google.com/docs/reference/android/com/google/firebase/database/DatabaseReference#push()). Is this what you want? – Alex Mamo Jul 10 '21 at 12:31

1 Answers1

0
 EditText plant = (EditText)findViewById(R.id.plantname);
    String pn = plant.getText().toString();

    FirebaseAuth mAuth;
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();




    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myref  = database.getReference("Plants");



    myref.child(System.currentTimeMillis()).child("Name").setValue(pn);
    myref.child(System.currentTimeMillis()).child("Latitude").setValue(lats);
    myref.child(System.currentTimeMillis()).child("Longitude").setValue(longs);