0

I am working on a simple app where you can retrieve video in viewpager not list view and user can also like video.

But now I want to sort all the videos on the basis of most liked.

Here is my database screenshot -

enter image description here

and her is the code of which I made a video adapter from which I retrieve video

code -

videoView.setVideoPath(obj.getUrl());
        title.setText(obj.getTitle());
        desc.setText(obj.getDesc());

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                pbar.setVisibility(View.GONE);
                mediaPlayer.start();
            }
        });

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });
    }

Update: Here is my updated database screenshot:

~

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ankit meena
  • 61
  • 1
  • 1
  • 6

1 Answers1

1

Firebase Realtime Database queries can only sort data on values that are stored in the database. There is no way to order on something that is calculated, like the number of child elements under the Likes/$postid node in your case.

The common workaround is to store the number of likes in the database too, for example as a LikeCount property, and then order on that.

You can securely have the client write its like/unlike and increment/decrement the counter by:

  • Using the increment() operation to perform the change atomically.
  • And using security rules to ensure each increment goes hand-in-hand with a new like.

For an example of this, see my answer here: Using Firebase Security Rules, how can I secure a node that has transactions run on it?


Once you have stored the the LikeCount you can sort on it by using a query. Something like:

DatabaseReference postsRef = FirebaseDatabase.getInstance().getReference("Posts");
Query query = postsRef.orderBy("LikeCount");
query.addValueEventListener(...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • @Frankn van Puffelen, Hey man I got it how to add like counter. Now please just tell me how I right query. – Ankit meena Jun 14 '21 at 11:17
  • This question is not answered yet you said to create a like counter which I did now here comes the main question of sorting of the database. Which I asked for. – Ankit meena Jun 14 '21 at 15:41
  • I added some info on that. But please don't change your question in the way you did, as right now the first part of my answer makes no sense when somebody later comes here. – Frank van Puffelen Jun 14 '21 at 15:51