Alexander
Alexander

Reputation: 41

Can only add one item to firebase

Can only add one item to firebase.

When I try to add a new item after adding the first one, it only updates the child on my first item. Not adding a second item. Everytime I click on save it should add a new item. But that is not what's happening.

Can somebody please help me?

Activity:

btnsavewishlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            SaveWishlist();

        }
    });


}

private void SaveWishlist() {

    Calendar calFordDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(calFordDate.getTime());

    postRandomName = saveCurrentDate;

    final String wishlist = spwishlisttitle.getSelectedItem().toString().trim();



    usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (dataSnapshot.exists()) {

                String userFirstname = dataSnapshot.child("fornavn").getValue().toString();
                String userProfileImage = dataSnapshot.child("profilbilde").getValue().toString();

                HashMap postMap = new HashMap();
                postMap.put("uid", current_user_id);
                postMap.put("date", saveCurrentDate);
                postMap.put("title", wishlist);
                postMap.put("profilbilde", userProfileImage);
                postMap.put("fornavn", userFirstname);
                wishListRef.child(current_user_id).child(current_user_id + postRandomName).updateChildren(postMap)
                        .addOnCompleteListener(new OnCompleteListener() {
                            @Override
                            public void onComplete(@NonNull Task task) {

                                if (task.isSuccessful()) {

                                    SendUserToMainActivity();
                                    Toast.makeText(WishListActivity.this, "Ønskeliste opprettet", Toast.LENGTH_SHORT).show();

                                } else {

                                    Toast.makeText(WishListActivity.this, "Error ocurred", Toast.LENGTH_SHORT).show();

                                }

                            }
                        });


            }

        }

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

        }
    });

Upvotes: 0

Views: 68

Answers (1)

Arno Abomo
Arno Abomo

Reputation: 46

Your postRandomName varaible will not change all the day. so for the same user, current_user_id + postRandomName will stay the same until next day. so you need a more better random value for postRandomName. You can just use postRandomName = String.valueOf(new Date().getTime()); It will give you a much better random string.

Upvotes: 2

Related Questions