<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by KTM on Medium]]></title>
        <description><![CDATA[Stories by KTM on Medium]]></description>
        <link>https://medium.com/@ktm-735600?source=rss-10c5296f8069------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fhAJTWz_IH-uJoP6.</url>
            <title>Stories by KTM on Medium</title>
            <link>https://medium.com/@ktm-735600?source=rss-10c5296f8069------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:17:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ktm-735600/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Video playing — using Exoplayer in viewpager2 and firebase db]]></title>
            <link>https://ktm-735600.medium.com/create-a-video-playing-app-using-exoplayer-in-viewpager2-and-firebase-db-56e35344bc35?source=rss-10c5296f8069------2</link>
            <guid isPermaLink="false">https://medium.com/p/56e35344bc35</guid>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[video-player]]></category>
            <category><![CDATA[tik-tok]]></category>
            <category><![CDATA[video-in-viewpager2]]></category>
            <category><![CDATA[list-of-videos]]></category>
            <dc:creator><![CDATA[KTM]]></dc:creator>
            <pubDate>Tue, 18 May 2021 12:11:42 GMT</pubDate>
            <atom:updated>2021-05-18T14:14:08.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Let us first begin with understanding what concepts we are using.</p><ol><li><strong>Firebase database</strong> — Firebase is a platform developed by Google for creating mobile and web applications.The <strong>Firebase</strong> Realtime <strong>Database</strong> is a cloud-hosted <strong>database. </strong>Data is stored as JSON and synchronised in realtime to every connected client.</li><li><strong>Android Viewpager 2 </strong>— <a href="https://developer.android.com/jetpack/androidx/releases/viewpager2">ViewPager2</a> is an improved version of the ViewPager library that offers enhanced functionality. It now supports Diffutil, layout direction, orientation etc.</li><li><strong>Exo player </strong>— ExoPlayer is an application level media player for Android. It provides an alternative to Android’s MediaPlayer API for playing audio and video both locally and over the Internet. ExoPlayer supports features not currently supported by Android’s MediaPlayer API, including DASH and SmoothStreaming adaptive playbacks. Unlike the MediaPlayer API, ExoPlayer is easy to customize and extend, and can be updated through Play Store application updates.</li></ol><p><strong>A. Pre-requisites</strong></p><p>I am adding some basic links on how to integrate firebase in your android app.</p><p>If not firebase you can just skip these steps and move forward to integrating viewpager2 and exoplayer. I am also using amazon s3 to store my video and image files, you can use firebase storage also or your own servers!</p><ol><li>Firebase Integration-</li></ol><p><a href="https://firebase.google.com/docs/android/setup">Add Firebase to your Android project | Firebase for Android</a></p><p>2. Setup Firebase database</p><p><a href="https://firebase.google.com/docs/database/android/start#java_1">Installation &amp; Setup on Android | Firebase Realtime Database</a></p><p>3. Add Exoplayer dependency and compile options to your app build.gradle.</p><p><a href="https://exoplayer.dev/hello-world.html">Hello world!</a></p><pre>compileOptions <strong>{<br>    </strong>// Support for Java 8 features<br>    coreLibraryDesugaringEnabled true<br>    sourceCompatibility JavaVersion.<em>VERSION_1_8<br>    </em>targetCompatibility JavaVersion.<em>VERSION_1_8<br></em><strong>}</strong></pre><blockquote>Exoplayer dependencies and Support for Java 8 features</blockquote><pre>coreLibraryDesugaring &#39;com.android.tools:desugar_jdk_libs:1.1.5&#39;<br><br>implementation &#39;com.google.android.exoplayer:exoplayer-core:2.13.0&#39;<br>implementation &#39;com.google.android.exoplayer:exoplayer-dash:2.13.0&#39;<br>implementation &#39;com.google.android.exoplayer:exoplayer-ui:2.13.0&#39;</pre><p><strong>B. LETS BEGIN THE JOURNEY!</strong></p><ol><li>I have already added my data to the firebase database and have a model class- GeneralPost that holds video post data as below.</li></ol><pre><em>@Parcelize<br>@IgnoreExtraProperties<br>@Keep<br>data class GeneralPost(<br>    @get:Exclude<br>    var id: String = &quot;&quot;,<br>    var post_media_type: PostMediaType = PostMediaType.NONE,<br>    var create_time: Long = 0,<br>    var media_url: String = &quot;&quot;,<br>    var description: String = &quot;&quot;,<br>    var user_id: String = &quot;&quot;,<br>    var likes: Int = 0,<br>    var followers: Int = 0,<br>    var comments: Int = 0,<br>    var user_name: String = &quot;&quot;<br>) : Parcelable</em></pre><p>2. Create your activity file to show your view pager . I have created a PostsActivity.kt. Add this peice of code to the layout of your activity.</p><pre><em>&lt;androidx.viewpager2.widget.ViewPager2<br>    android:id=&quot;@+id/vpPost&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot; /&gt;</em></pre><p>3. Create an adapter class as below for viewpager to render data. In my case i have created a GeneralPostsAdapter.kt. The adapter is extending the FirebaseRecyclerAdapter. For using this we need to add a dependency in out build.gradle.</p><pre><em>implementation &#39;com.firebaseui:firebase-ui-database:6.3.0</em></pre><p>The adapter will ask you to implement few methods- OnCreateViewHolder and OnBindViewHolder. Just follow it .</p><pre><em>class GeneralPostsAdapter(options:FirebaseRecyclerOptions&lt;GeneralPost&gt;) :<br>    FirebaseRecyclerAdapter&lt;GeneralPost, GeneralPostsAdapter.VideoViewHolder&gt;(options)</em></pre><p>4. Now setup your viewpager2 by providing it data from firebase using FirebaseRecyclerOptions in your activity file.</p><pre><em>val options = FirebaseRecyclerOptions.Builder&lt;GeneralPost&gt;()<br>         .setQuery(FirebaseDatabase.getInstance().getReference(Constants.NODE_GENERAL_POSTS),GeneralPost::class.java)<br>.build()</em></pre><pre><em>val postsAdapter =GeneralPostsAdapter(options)<br>vpPost.adapter = postsAdapter //set the adapter to your viewpager.</em></pre><p>As we have used the <em>FirebaseRecyclerAdapter, </em>we can let our adapter get updated whenever there is any change in data by asking it to listen. Simply, set the adapter to start listening and stop listening in your activity file.</p><pre><em>override fun onStart() {<br>    super.onStart()<br>    postsAdapter.startListening()<br>}</em></pre><pre><em>override fun onStop() {<br>    super.onStop()<br>    postsAdapter.stopListening()<br> }</em></pre><h4><strong>5. Create an .xml layout file to hold the view for our viewpager item.</strong></h4><p><a href="https://media.giphy.com/media/Euep9OGNL0TutamVKS/giphy.gif"><strong><em>NOTE</em></strong></a>:-</p><p>Major problems with exoplayer that i have been playing around for days when i used it in viewpager or a recyclerview.</p><p>a. Videoplaying success on first time but when scrolling back to previous played videos , only buffering and black screen. <strong>MediaCodecVideoRenderer error.</strong></p><p>b. App crashing after few videos are rendered and scrolling back forth.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FNQ0aki2pY46Vq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FNQ0aki2pY46Vq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FNQ0aki2pY46Vq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="484" frameborder="0" scrolling="no"><a href="https://medium.com/media/a080997d3c7af84917436bee7d94e630/href">https://medium.com/media/a080997d3c7af84917436bee7d94e630/href</a></iframe><h3>Solution:-</h3><p>a. In each view holder , store a seperate instance of exoplayer and the exoplayer view. Dynamically adding and removing the exoplayer view during view attach and detach.</p><p>b. ExoPlayerView object with no SimpleExoPlayer attached during Bind Time. Attach during view attach.</p><p>c. Stop the player of the view holder when view changes.</p><p>d. Stop the player position when activity goes in onStop().</p><p>So lets begin following all of the above:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FEuep9OGNL0TutamVKS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FEuep9OGNL0TutamVKS%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FEuep9OGNL0TutamVKS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/68df36f5a95f407c1638aa5de068b17d/href">https://medium.com/media/68df36f5a95f407c1638aa5de068b17d/href</a></iframe><p>6. Layout file just has a frame layout as we render things dynamically. My item file is called item_post.xml.</p><pre><em>&lt;FrameLayout     xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:background=&quot;@color/grey&quot;<br>    android:id=&quot;@+id/llParent&quot;<br>    android:padding=&quot;1dp&quot;/&gt;</em></pre><p>A Util class here —</p><pre><em>public class VideoPlayerConfig {<br>    //Minimum Video you want to buffer while Playing<br>    public static final int MIN_BUFFER_DURATION = 2000;<br>    //Max Video you want to buffer during PlayBack<br>    public static final int MAX_BUFFER_DURATION = 5000;<br>    //Min Video you want to buffer before start Playing it<br>    public static final int MIN_PLAYBACK_START_BUFFER = 1500;<br>    //Min video You want to buffer when user resumes video<br>    public static final int MIN_PLAYBACK_RESUME_BUFFER = 2000;<br>}</em></pre><p>7. Lets move to the viewholder now. Create a method called setData in your viewholder class. I am simply using the sparseArrays to store the instances of exoplayer and its playerview that are created in each view holder.</p><pre><em>class VideoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){<br><br>    private var videoSurfaceDefaultHeight = 0<br>    private var screenDefaultHeight = 0<br>    private lateinit var videoPlayerView: PlayerView<br><br>    fun setData(<br>        data: GeneralPost,<br>        position: Int,<br>        mStoredMedias: SparseArray&lt;String&gt;,<br>        mStoredPlayers: SparseArray&lt;SimpleExoPlayer&gt;,<br>        mStoredPlayerView: SparseArray&lt;PlayerView&gt;<br>    ) <br>{<br>mStoredMedias.append(position, data.media_url)<br>mStoredPlayerView.append(position,getVideoSource(itemView.context))<br>mStoredPlayers.append(position, getVPlayer(itemView.context))<br>}</em></pre><p>Create a method to get simpleExoplayer in the viewholder.</p><pre><em>private fun getVPlayer(context: Context): SimpleExoPlayer <br>{<br>val loadControl: LoadControl = DefaultLoadControl.Builder()<br>.setAllocator(DefaultAllocator(true, 16))<br>.setBufferDurationsMs(VideoPlayerConfig.MIN_BUFFER_DURATION,<br>                VideoPlayerConfig.MAX_BUFFER_DURATION,<br>                VideoPlayerConfig.MIN_PLAYBACK_START_BUFFER,<br>                VideoPlayerConfig.MIN_PLAYBACK_RESUME_BUFFER)<br> .setTargetBufferBytes(-1)<br>   .setPrioritizeTimeOverSizeThresholds(true).createDefaultLoadControl)<br><br>// Create a progressive media source pointing to a streamuri.<br>    val player = SimpleExoPlayer.Builder(context)<br>            .setLoadControl(loadControl)<br>            .build()<br>   return player<br>}</em></pre><p>Create a method to get the dynamically create simple exoplayer view in the view holder.</p><pre><em>private fun getVideoSource(mContext: Context): PlayerView {<br>        val display =(mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay<br>        val point = Point()<br>        display.getSize(point)<br><br>        videoSurfaceDefaultHeight = point.x<br>        screenDefaultHeight = point.y<br>        videoPlayerView = PlayerView(mContext)<br>        videoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM)<br>        videoPlayerView.useController = false<br>        videoPlayerView.setShowBuffering(PlayerView.SHOW_BUFFERING_WHEN_PLAYING)<br>      return videoPlayerView<br>    }<br>}</em></pre><h3>8. THE CATCH POINT</h3><p>Override the on detach and attach methods in the adapter class to handle the stop and play of the videos in exoplayer :)</p><pre><em>override fun onViewDetachedFromWindow(holder: VideoViewHolder) {<br>    super.onViewDetachedFromWindow(holder)<br><br>    val adapterPosition = holder.adapterPosition<br>    val indexOfChild = holder.itemView.llParent.indexOfChild<br>(mStoredPlayerView.get(adapterPosition))<br>    if (indexOfChild &gt;= 0) <br>{<br></em><strong><em>        //remove the player view from parent view and stop player<br></em></strong><em>        holder.itemView.llParent.removeViewAt(indexOfChild)<br>        mStoredPlayers.get(adapterPosition).stop()<br>    }<br>}</em></pre><p>OnView Attached, just create a new mediasource and set it to the existing player of the viewholder.</p><pre><em>override fun onViewAttachedToWindow(holder: VideoViewHolder) {<br>    super.onViewAttachedToWindow(holder)<br>   <br>    val adapterPosition = holder.adapterPosition<br>    val mediaitem = mStoredMedia.get(adapterPosition)<br>    val dataSourceFactory: DataSource.Factory =<br>        DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext, &quot;APPNAME&quot;))<br>    val mediaSource:MediaSource =ProgressiveMediaSource<br>        .Factory(dataSourceFactory)<br>        .createMediaSource(MediaItem.fromUri(mediaitem))</em></pre><pre><strong><em>//get the existing instances of exoplayer and exoplayer view<br></em></strong><em>    val playerView = mStoredPlayerView.get(adapterPosition)<br>    val player: SimpleExoPlayer=mStoredPlayers.get(adapterPosition)<br><br>    player.setMediaSource(mediaSource, true)<br>    player.prepare()<br>    player.playWhenReady = true<br>    playerView.player = player<br></em><strong><em>   //add player view again to parent<br></em></strong><em>    holder.itemView.llParent.addView(playerView)<br><br>}</em></pre><p>9. Finally Adapter shall bind with the created viewholder.</p><pre><em>private val mStoredMedia: SparseArray&lt;String&gt; = SparseArray&lt;String()<br>private val mStoredPlayers: SparseArray&lt;SimpleExoPlayer&gt; = SparseArray&lt;SimpleExoPlayer&gt;()<br>private val mStoredPlayerView: SparseArray&lt;PlayerView&gt; = SparseArray&lt;PlayerView&gt;()</em></pre><pre><em>override fun onCreateViewHolder(<br>    parent: ViewGroup,<br>    viewType: Int): VideoViewHolder {<br>    mContext = parent.context<br>    val view: View = LayoutInflater.from(parent.getContext())<br>        .inflate(R.layout.item_post, parent, false)<br>    return VideoViewHolder(view)<br>}</em></pre><pre><em>override fun onBindViewHolder(holder: VideoViewHolder, position: Int, model: GeneralPost) {<br><br>    holder.setData(<br>        model,<br>        position,<br>        mStoredMedia,<br>        mStoredPlayers,<br>        mStoredPlayerView<br>    )<br>}</em></pre><p>10. To stop the playing videos if any on activity closing, we need to get the playing position in adapter and stop the player and remove player view of that viewholder. Thats it!</p><p>My internet just seems a bit flaky to load videos tho. You can handle the configuration of loadcontroller for exoplayer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F551854471%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F551854471&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1140226528_295x166&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="340" height="640" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3b8816d10c1e7b9661dfbf3cad3134b/href">https://medium.com/media/a3b8816d10c1e7b9661dfbf3cad3134b/href</a></iframe><p>THANK YOU AND BEST LUCK !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56e35344bc35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>