Skip to content
Advertisement

Why counter just increase to 1 in firebase?

im trying to increase a visitor counter views when access to read a message, so i made a method called incrementar () and set it where i retrieve info when someone click to open that post. But i dont know why only increase to 1 view in firebase, if i click again it does not increase. should use shared preferences? or there is an other method to increase a counter from firebase?

int views;
int score;
int increment = +1;
DatabaseReference ref;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    setTitle("Chatroom");

    threadNameTV = findViewById(R.id.threadNameTV);
    newMessageET = findViewById(R.id.newMessageET);
    homeButton = findViewById(R.id.homeButton);
    sendButton = findViewById(R.id.sendButton);
    messagesLV = findViewById(R.id.messagesLV);
    final View messageview = getLayoutInflater().inflate(R.layout.messages_listview, null);
    messageTV = messageview.findViewById(R.id.messageTV);


    mAuth = FirebaseAuth.getInstance();
    currentUserId = mAuth.getCurrentUser().getUid();
    user = mAuth.getCurrentUser();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    firebaseUser = mAuth.getCurrentUser();
    UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
    UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");


    threadNameTV.setTextColor(Color.parseColor("#000000"));

    if (getIntent() != null && getIntent().getExtras() != null) {
        if (getIntent().getExtras().containsKey("messageThreadDetails")) {
            messageThread = (MessageThread) getIntent().getSerializableExtra("messageThreadDetails");
            threadNameTV.setText(messageThread.title);
            getMessages(messageThread.thread_id);
            incrementar();
        }
    } else {
        Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
    }

    homeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (user != null) {
                user = null;
                mDatabase = null;
                mAuth = null;
                Intent intent = new Intent(ChatActivity.this, ThreadsActivity.class);
                startActivity(intent);
                finish();
            } else {
                user = null;
                mDatabase = null;
                mAuth = null;
                Toast.makeText(ChatActivity.this, "You need to login", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ChatActivity.this, IniciarSesion.class);
                startActivity(intent);
                finish();
            }
        }
    });

    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String message = newMessageET.getText().toString();
            String user_name = user.getDisplayName();
            String profileimage = user.getPhotoUrl().toString();
            if (message.isEmpty()) {
                Toast.makeText(ChatActivity.this, "Enter Message", Toast.LENGTH_SHORT).show();
            } else {
                addMessage(message, user_name, profileimage, messageThread.thread_id);
            }
        }
    });

}

public void addMessage(String message, String user_name, String profileimage, String thread_id) {
    if (user != null) {
        mDatabase.child("Normas").child(thread_id).child("messages").push().setValue(new Message(message, user.getUid(), user_name, profileimage, new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.US).format(new Date())));
        newMessageET.setText("");
    } else {
        Toast.makeText(this, "No user logged in", Toast.LENGTH_SHORT).show();
    }
}


public void getMessages(String thread_id) {
    mDatabase.child("Normas").child(thread_id).child("messages").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            messagesList.clear();
            for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
                Message message = messageSnapshot.getValue(Message.class);
                if (message != null) {
                    message.message_id = messageSnapshot.getKey();
                    Log.d(TAG, "onDataChange: " + message.toString());
                }
                messagesList.add(message);
            }
            messagesAdapter = new MessagesAdapter(ChatActivity.this, R.layout.threads_listview, messagesList, ChatActivity.this);
            messagesLV.setAdapter(messagesAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(ChatActivity.this, "ChatActivity: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}


@Override
public void deleteMessage(String message_id) {
    mDatabase.child("Normas").child(messageThread.thread_id).child("messages").child(message_id).removeValue();
}

public void setimage() {
    UsersRef.child(currentUserId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NotNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                if (dataSnapshot.hasChild("profileimage")) {
                    String image = dataSnapshot.child("profileimage").getValue().toString();
                    Picasso.with(ChatActivity.this).load(image).placeholder(R.drawable.profilefoto).into(fotoforos);

                }
            }
        }

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

        }
    });


}



public void incrementar() {
    FirebaseDatabase.getInstance().getReference().child("Normas").child(messageThread.thread_id).child("views").setValue(increment);


}

}

Thanks so much

Advertisement

Answer

You’re setting +1 as the value each time you call:

int increment = +1;
FirebaseDatabase.getInstance().getReference().child("Normas")
    .child(messageThread.thread_id).child("views").setValue(increment);

What would work is:

FirebaseDatabase.getInstance().getReference().child("Normas")
    .child(messageThread.thread_id).child("views").setValue(ServerValue.increment(1));

Instead of sending the literal value 1, this second snippet sends an instruction to increment the current value by 1.

Advertisement