简体   繁体   中英

How to avoid downloading data from online storage (Firebase) every time an item shows in a RecyclerView?

I have some videos saved in Firebase storage, and the Url for them are saved in Realtime Database, all from firebase. All the videos are shown in a VideoView inside a RecyclerView.

This is the code i use to retreive data from the database:

 DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference ref = rootRef.child("videos");
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                VideoModel model = dataSnapshot.getValue(VideoModel.class);
                list.add(model);
                adapter.notifyDataSetChanged();
                
            }

        }

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

        }
    });

And this is the code I use to download the video from the URL (this method is called inside my adapter's onBindViewHolder ):

private void setVideoUrl(VideoModel model,MyViewHolder holder){

    String url = model.getUrl();

    Uri uri = Uri.parse(url);
    holder.videoView.setVideoURI(uri);
    MediaController mediaController = new MediaController(context);
    holder.videoView.setMediaController(mediaController);
    mediaController.setAnchorView(holder.videoView);

    holder.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {

            holder.videoView.seekTo(1);

        }
    });

}

This works fine, but the problem is that if i scroll the recyclerView down, and then back up, all the videos previously downloaded will be downloaded again. Is there a way to prevent this repeated download to happen?

You can download your videos to the temp folder on device before setting up your recycler view and store all the temp file uri in an arraylist in the same order as the other data passed to you recycler view adapter and pass the arraylist to your adapter along with other data. then in onBindViewHolder, you can just retrieve the already downloaded files and play them. this way, downloading the videos doesn't have anything to do with the views binding to your recycler view.

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