简体   繁体   中英

Firebase create a new object every time I click a button

I have a problem/ question. I want to save different objects to firebase realtime database every time I click a button, but I have a problem because, since I have a Shopping list I click more items and I want to save them to the database but it saves just the last item I clicked and I want to understand what I'm doing wrong. I'm new to Android / Firebase, it's the first time I'm doing it so if anyone can tell me what I'm doing wrong it would be awesome. Thank you so much. I will attach the code and the photo of the database.

Activity :

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;
int position=0;
String searchText="";

private RecyclerView mResultList;
private DatabaseReference mUserDatabase;



public static int cart_count = 0;



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




    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = findViewById(R.id.search_field);
    mSearchBtn   = findViewById(R.id.search_btn);
    mResultList  = findViewById(R.id.result_list_cart);
    AddToCart    = findViewById(R.id.imageButton2);
    Cart         = findViewById(R.id.cartButton);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchText = mSearchField.getText().toString();
            firebaseUserSearch(searchText);
        }
    });

    Cart.setOnClickListener(new View.OnClickListener() {
        private Object Tag="Activity";

        @Override
        public void onClick(View v) {
            if (cart_count < 1) {

            } else {
                startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
            }
        }
    });
}



private void firebaseUserSearch(String searchText) {
    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
    Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery
    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {

            viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
            viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
        }
    };
    mResultList.setAdapter(firebaseRecyclerAdapter);
}


@Override
protected void onStart() {
    super.onStart();
    invalidateOptionsMenu();
}

// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;
    String nome;
    String surname;
    Long prezzo;
    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);

        addToCart.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                Users a = new Users(nome,surname,prezzo);
                FirebaseDatabase database = FirebaseDatabase.getInstance();
                DatabaseReference myRef = database.getReference("Cart");
                myRef.setValue(a);
            }
        });
    }

    public void getDetails(String name,String cognome,Long price){
        nome=name;
        surname=cognome;
        prezzo=price;
    }


    public void setDetails(String name, String surname, Long price) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
        TextView user_price = (TextView)mView.findViewById(R.id.price);

        user_name.setText(name);
        user_surname.setText(surname);
        user_price.setText(Long.toString(price));

    }
}




}

enter code here

You need to use the push() method:

myRef.push().setValue(a);

Currently the last data you are adding is overriding the data before it. The push() method will create a random ID and separate each user.

Or if you are using firebase authentication then you can use the user uid instead of push() to separate each user that you are saving.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM