<repo_name>Chrizlove/YoutubePlayer<file_sep>/app/src/main/java/com/example/youtubeplayer/MainActivity.kt
package com.example.youtubeplayer

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.inputmethod.InputMethodManager
import android.widget.SearchView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.youtube.player.YouTubeApiServiceUtil
import com.google.android.youtube.player.YouTubeBaseActivity
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubePlayer
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class MainActivity : AppCompatActivity() {
    private lateinit var youtubeadapter: YoutubeVideoAdapter
    private lateinit var videosList: List<YoutubeVideo>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //code for entire searchview to be clivkable
        searchbar.setOnClickListener {
            searchbar.isIconified = false
        }

        //showing hint when searchview is tapped on
        searchbar.queryHint = "Search for videos"

        //preload some videos
        getVideosList("")

        //code for onsubmit of searchview query
        searchbar.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(keyword: String?): Boolean {

                //fetch list of videos
                keyword?.let {
                    getVideosList(it)
                }

                //hiding keyboard when submit button is pressed
                val keyboard = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                keyboard.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
                return true
            }
            override fun onQueryTextChange(p0: String?): Boolean {
                return false
            }
        })
    }

    private fun setUpRecyclerView(videos: List<YoutubeVideo>) {
        youtubeadapter = YoutubeVideoAdapter(this, videos)
        val layoutManager =  LinearLayoutManager(this)
        ytVideosRecycler.layoutManager= layoutManager
        ytVideosRecycler.adapter = youtubeadapter

        //listener for video click and to change activity to play the video

        youtubeadapter.setOnItemClickListener(object: YoutubeVideoAdapter.onItemClickListener{
            override fun onItemClick(position: Int) {
                val intent = Intent(applicationContext, YoutubeVideoPlayerActivity::class.java)
                intent.putExtra("title",videos[position].snippet.title)
                intent.putExtra("desc",videos[position].snippet.description)
                intent.putExtra("videoId",videos[position].id.videoId)
                startActivity(intent)
            }
        })
    }

    private fun getVideosList(keyword: String) {
        val videos = RetrofitInstance.youtubeapi.getYoutubeVideos("snippet",keyword,"<KEY>",10,"video")
        videos.enqueue(object : Callback<YoutubeAPIData?> {
            override fun onResponse(call: Call<YoutubeAPIData?>, response: Response<YoutubeAPIData?>) {
                 videosList = response.body()?.items!!
                //setting up recycler view
                videosList?.let { setUpRecyclerView(it) }
            }
            override fun onFailure(call: Call<YoutubeAPIData?>, t: Throwable) {
                Toast.makeText(applicationContext, "Unable to fetch results!", Toast.LENGTH_SHORT).show()
                Log.d("APIError",t.toString())
            }
        })
    }
}<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeAPIData.kt
package com.example.youtubeplayer

data class YoutubeAPIData (val items: List<YoutubeVideo>)
<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeListApi.kt
package com.example.youtubeplayer

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query


interface YoutubeListApi {
    @GET("search")
    fun getYoutubeVideos(@Query ("part") part: String,
                         @Query(value="q") keyword: String,
                         @Query(value="key") key: String,
                         @Query("maxResults") max: Int,
                         @Query("type") type: String): Call<YoutubeAPIData>
}<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeAPIDatahigh.kt
package com.example.youtubeplayer

data class YoutubeAPIDatahigh (val url: String)<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeAPIid.kt
package com.example.youtubeplayer

data class YoutubeAPIid (val videoId: String)<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeAPIsnippet.kt
package com.example.youtubeplayer

data class YoutubeAPIsnippet( val title: String, val description: String, val thumbnails: YoutubeAPIthumbnails)<file_sep>/app/src/main/java/com/example/youtubeplayer/RetrofitInstance.kt
package com.example.youtubeplayer

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitInstance {
    const val BASE_URL = "https://www.googleapis.com/youtube/v3/"
    private val retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
    val youtubeapi: YoutubeListApi by lazy {
        retrofit.create(YoutubeListApi::class.java)
    }
}<file_sep>/README.md
# YoutubePlayer

A basic app with 2 activities, 
1st where is a home screen and user can search for videos and those videos fetched will be displayed.
2nd is a player screen where the video clicked on the home screen will play.

Checkout the app- https://drive.google.com/file/d/1QtgDb7dkjXZNhzGXOAQYjLfnpGuoUZ48/view?usp=sharing

<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeAPIthumbnails.kt
package com.example.youtubeplayer

data class YoutubeAPIthumbnails(val high: YoutubeAPIDatahigh)<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeVideoAdapter.kt
package com.example.youtubeplayer

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class YoutubeVideoAdapter(private val context: Context, private val videos: List<YoutubeVideo>): RecyclerView.Adapter<YoutubeVideoAdapter.YoutubeVideoHolder>() {

    inner class YoutubeVideoHolder(itemView: View, listener: onItemClickListener): RecyclerView.ViewHolder(itemView) {
        val videoTitle = itemView?.findViewById<TextView>(R.id.videoTitleTextView)
        val vidThumbnail = itemView?.findViewById<ImageView>(R.id.thumbnailImageView)
        init{
            itemView.setOnClickListener {
                listener.onItemClick(adapterPosition)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): YoutubeVideoHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.lyt_ytvideo, parent, false)
        return YoutubeVideoHolder(view,mListener)
    }

    override fun onBindViewHolder(holder: YoutubeVideoHolder, position: Int) {
        val currentVideo = videos[position]
        holder?.videoTitle.text = currentVideo.snippet.title
        Glide.with(holder?.vidThumbnail.context).load(currentVideo.snippet.thumbnails.high.url).into(holder?.vidThumbnail)
    }

    override fun getItemCount(): Int {
        return videos.size
    }
    private lateinit var mListener: onItemClickListener

    interface onItemClickListener{
        fun onItemClick(position: Int)
    }
    fun setOnItemClickListener(listener: onItemClickListener) {
        mListener = listener
    }
}<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeVideoPlayerActivity.kt
package com.example.youtubeplayer

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.google.android.youtube.player.YouTubeBaseActivity
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubePlayer
import kotlinx.android.synthetic.main.activity_youtube_video_player.*

class YoutubeVideoPlayerActivity : YouTubeBaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_youtube_video_player)

        //recieving intents
        val videotitle:String = intent.getStringExtra("title").toString()
        val videoDesc:String = intent.getStringExtra("desc").toString()
        val videoId:String = intent.getStringExtra("videoId").toString()
        Log.d("title",videotitle)

        //setting title and desc of videos
        titleText.text = videotitle
        descText.text = videoDesc
        //loading the player
        initalizePlayer(videoId)
    }

    private fun initalizePlayer(videoId: String) {
        youtubePlayerView.initialize(getString(R.string.youtube_api_key),object: YouTubePlayer.OnInitializedListener{
            override fun onInitializationSuccess(
                p0: YouTubePlayer.Provider?,
                p1: YouTubePlayer?,
                p2: Boolean
            ) {
                //playing video
                p1?.loadVideo(videoId)
                p1?.play()
            }

            override fun onInitializationFailure(
                p0: YouTubePlayer.Provider?,
                p1: YouTubeInitializationResult?
            ) {
                Toast.makeText(applicationContext,"Something went wrong",Toast.LENGTH_LONG).show()
            }

        })
    }
}<file_sep>/app/src/main/java/com/example/youtubeplayer/YoutubeVideo.kt
package com.example.youtubeplayer

import android.graphics.Bitmap

data class YoutubeVideo(val id: YoutubeAPIid, val snippet: YoutubeAPIsnippet)