how to include a new item in the same user id already included?

0

I'm creating an app for the first time, I'm new, but I'm learning. However, I hired the inclusion of a new data in the same user of a certain product. I've seen a few examples and studied query, push, and other documentation. In the simple code the inclusion is done successfully, but I did not want to include the same product already included in the database, if it already exists. How do I, follow the inclusion and search code:

private void salvarCotacao() {
    final String idUser = mAuth.getCurrentUser().getUid();
    //Define a ID do usuário logado no sistema
    final String idPro = spProduto.getSelectedItem().toString();
    //Define o produto a ser cadastrado

    Query pesqNm;
    //Começa uma pesquisa por ID do usuário cadastrado
    pesqNm = ConfiguracaoFirebase.getFirebase()
            .child("bd_cotacoes").orderByChild("nome").equalTo(idUser);
    //A ID do usuário cadastrado é igual ao campo nome no firebase do nó bd-cotacoes
    pesqNm.addValueEventListener(new ValueEventListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                //Aqui verifica se existe os dados
                for (DataSnapshot objSnapshot:dataSnapshot.getChildren()) {
                    // Se existe começa a pesquisa
                    if (Objects.equals(objSnapshot.child("nome").getValue(), idUser)) {
                        // Se encontra a ID do usuário no banco continue, se não sai...
                        if (!Objects.equals(objSnapshot.child("produtoCotacao").getValue(), idPro)) {
                            //Se não encontrar o produto a ser cadastrado (String idPro)
                            // igual no banco firebase (bd_cotacoes) do ID do usuário pesquisado, cadastre
                            cotacoes.salvarCT();
                        }else {
                            //Se encontrar o produto a ser cadastrado (String idPro), avise...
                            Toast toast1 = Toast.makeText(CotacaoActivity.this, "Produto já Cadastrado", Toast.LENGTH_LONG);
                            toast1.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
                            toast1.show();
                        }
                    }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

What's wrong there. It searches, finds the item, saves a new one, but does not take the search into consideration and includes the same existing product. In if() , does the search and saves, but it passes else and makes the warning. It's like I have not seen the conditions. Can anyone help me out here?

    
asked by anonymous 31.08.2018 / 16:58

0 answers