How to use MediaStore - android

I am making a small music player, I want to make the typical recyclerview that shows all the songs that are on the device. The problem is that I'm very new to using MediaStore and I don't really understand how it works. I have read the documentation and several articles, but I can't understand it very well. This is what I have done for the moment and I don't know if it is enough or if something is missing. I would be grateful if someone could show me how to achieve what I want to do.
MAIN ACTIVITY:
class MainActivity : AppCompatActivity() {
private lateinit var mBinding : ActivityMainBinding
private lateinit var mSongAdapter : SongAdapter
private lateinit var mLinearLayoutManager : LinearLayoutManager
private var mSongs = listOf<Song>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
initSongs()
initRecycler()
}
override fun onStop() {
super.onStop()
Log.i("Canciones:", mSongs.toString())
}
private fun initSongs() {
GlobalScope.launch{
mSongs = querySongs()
}
}
private fun initRecycler() {
mSongAdapter = SongAdapter(mSongs)
mLinearLayoutManager = LinearLayoutManager(this)
mBinding.rvCanciones.apply {
setHasFixedSize(true)
layoutManager = mLinearLayoutManager
adapter = mSongAdapter
}
}
private suspend fun querySongs() : List<Song> {
val songs = mutableListOf<Song>()
withContext(Dispatchers.IO){
val projection = arrayOf(
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.SIZE
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
application.contentResolver.query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null
)?.use { cursor ->
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)
val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
val sizeColum = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)
while (cursor.moveToNext()){
val id = cursor.getLong(idColumn)
val name = cursor.getString(nameColumn)
val duration = cursor.getFloat(durationColumn)
val size = cursor.getString(sizeColum)
val contentUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id
)
val song = Song(contentUri, name, duration, size)
songs += song
}
}
} else {
}
}
return songs
}
}
SONG DATA CLASS:
data class Song(
val uri : Uri,
val name : String,
val duration : Float,
val size : String
)

Related

How to get Folder size and number of Files avaliable from Folder path in Kotlin

i am trying to create a video player app using kotlin , First of all I got the videos files by using MediaStore , than store this in ArrayList so far it's been perfect but When I made a folder list of videos, I tried to find out the size of those folders and how many video files there are in those folders, but I failed. like this (Image)
Check this image for more clear
This is my data class code (VideoItem.Kt)
import android.net.Uri
data class VideoItem(
val id: String,
val title: String,
val duration: Long = 0,
val folderName: String,
val size: String,
val path: String,
val dateAdded: String,
val artUri: Uri
)
data class FolderItem(
val id: String,
val folderName: String,
val folderSize: Long
)
This is my MainActivity Code To get Allvideos Using MediaStore
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
companion object {
lateinit var videoList: ArrayList<VideoItem>
lateinit var folderList: ArrayList<FolderItem>
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
folderList = ArrayList()
videoList = getAllVideos()
setFragment(VideoviewFragment())
}
private fun setFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.FrameLayout, fragment)
transaction.disallowAddToBackStack()
transaction.commit()
}
#SuppressLint("Recycle", "Range")
private fun getAllVideos(): ArrayList<VideoItem> {
val tempList = ArrayList<VideoItem>()
val tempFolderList = ArrayList<String>()
val projection = arrayOf(
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media._ID,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DATE_ADDED,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.BUCKET_ID
)
val cursor = this.contentResolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
MediaStore.Video.Media.DATE_ADDED + " DESC"
)
if (cursor != null)
if (cursor.moveToNext())
do {
val titleC =
cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE))
val idC = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID))
val folderNameC =
cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.BUCKET_DISPLAY_NAME))
val folderIdC =
cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.BUCKET_ID))
val sizeC = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.SIZE))
val pathC = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA))
val dateAddedC =
cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATE_ADDED))
val durationC =
cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DURATION))
.toLong()
try {
val file = File(pathC)
val artUriC = Uri.fromFile(file)
val video = VideoItem(
title = titleC,
id = idC,
folderName = folderNameC,
size = sizeC,
path = pathC,
duration = durationC,
dateAdded = dateAddedC,
artUri = artUriC
)
if (file.exists()) tempList.add(video)
//for adding Folders
if (!tempFolderList.contains(folderNameC)) {
tempFolderList.add(folderNameC)
val folderSizeC = getFileLength(pathC)
folderList.add(
FolderItem(
id = folderIdC,
folderName = folderNameC,
folderSize = folderSizeC
)
)
}
} catch (_: Exception) {
}
} while (cursor.moveToNext())
cursor?.close()
return tempList
}
private fun getFileLength(path: String?): Long {
return if (!isExistFile(path)) 0 else File(path.toString()).length()
}
private fun isExistFile(path: String?): Boolean {
val file = File(path.toString())
return file.exists()
}
}
This is my RecyclerviwAdapter Code(FolderAdapter.kt)
class FoldersAdapter(private val context: Context, private var foldersList: ArrayList<FolderItem>) :
RecyclerView.Adapter<FoldersAdapter.MyHolder>() {
class MyHolder(binding: FolderItemBinding) : RecyclerView.ViewHolder(binding.root) {
val folderName = binding.folderName
val noofFiles = binding.nooffiles
val folderSize = binding.foldersize
val root = binding.root
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
return MyHolder(FolderItemBinding.inflate(LayoutInflater.from(context), parent, false))
}
override fun onBindViewHolder(holder: MyHolder, position: Int) {
holder.folderName.text = foldersList[position].folderName
val size: Long = foldersList[position].folderSize
holder.folderSize.text = android.text.format.Formatter.formatFileSize(context, (size))
holder.root.setOnClickListener {
val intent = Intent(context, FolderVideosActivity::class.java)
intent.putExtra("position", position)
ContextCompat.startActivity(context, intent, null)
}
}
override fun getItemCount(): Int {
return foldersList.size
}
}
This is my all codes now please check out all code and suggest the best.
Thank you
Use this function for size
private fun getFolderSize(f: File): Long {
var size: Long = 0
if (f.isDirectory) {
for (file in f.listFiles()!!) {
size += getFolderSize(file)
}
} else {
size = f.length()
}
return size
}
And Count number of files Use this
val length = File("/path/to/folder").listFiles()?.size

Android: cannot play a song - java.lang.UnsupportedOperationException: Unknown or unsupported URL

I'm trying to play a song which I put in Music folder on SD card. But when I call
mediaPlayer?.setDataSource(this#MusicPlayerActivity, uri)
I get the exception: "java.lang.UnsupportedOperationException: Unknown or unsupported URL: content://media/external/audio/media/samurai.mp3"
I get an URI in the readSongs() function. Is there any trouble with the URI? If there is, how to get the right URI?
Thanks.
Code snippet
class MusicPlayerActivity : AppCompatActivity() {
private lateinit var binding: ActivityMusicPlayerBinding
private lateinit var musicList: MutableList<Music>
private lateinit var linearLayoutManager: LinearLayoutManager
private lateinit var adapter: MusicAdapter
private var mediaPlayer: MediaPlayer? = null
private var currentTrackPosition: Int = 0
private var isPlaying: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMusicPlayerBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
musicList = mutableListOf()
if (Build.VERSION.SDK_INT >= 23) {
checkPermissions()
}
binding.playFab.setOnClickListener {
play(currentTrackPosition)
}
}
private fun play(currentTrackPosition: Int) {
if (!isPlaying) {
isPlaying = true
mediaPlayer = MediaPlayer()
mediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
try {
val uri = Uri.parse(musicList[currentTrackPosition].songUri)
mediaPlayer?.setDataSource(this#MusicPlayerActivity, uri)
mediaPlayer?.prepare()
mediaPlayer?.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun readSongs() {
val selection = MediaStore.Audio.Media.IS_MUSIC
val projection = arrayOf(
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME
)
val uriExternal = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor? = contentResolver.query(
uriExternal,
projection,
selection,
null, null
)
while (cursor!!.moveToNext()) {
musicList.add(
Music(
cursor.getString(0),
cursor.getString(1),
Uri.withAppendedPath(uriExternal, cursor.getString(2)).toString()
)
)
}
cursor.close()
linearLayoutManager = LinearLayoutManager(this)
adapter = MusicAdapter(musicList)
binding.recyclerView.layoutManager = linearLayoutManager
binding.recyclerView.adapter = adapter
}
I replaced MediaStore.Audio.Media.DISPLAY_NAME with MediaStore.Audio.Media._ID so URI becomes "content://media/external/audio/media/42" and now it works!

List size + position too large, last item in list beyond totalCount

I'm trying to get device contacts using paging library (3.0.0-alpha02 version). But when I try to invalidate the data source I get this exception:
java.lang.IllegalArgumentException: List size + position too large, last item in list beyond totalCount.
Here's my code.
Data Class:
data class Contact(
val id: Long,
val lookupUri: Uri,
val name: String?,
val photoUri: Uri?
)
DataSource:
class ContactsDataSource(private val contentResolver: ContentResolver) : PositionalDataSource<Contact>() {
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<Contact>) {
val totalSize = getRowsNumbers()
val firstLoadPosition = computeInitialLoadPosition(params, totalSize)
val firstLoadSize = computeInitialLoadSize(params, firstLoadPosition, totalSize)
val list = contentResolver.query(
ContactsContract.Contacts.CONTENT_URI,
CONTACT_PROJECTION,
null,
null,
"${CONTACT_PROJECTION[2]} ASC LIMIT $firstLoadSize OFFSET $firstLoadPosition"
)?.use {
getRows(it)
}!!
callback.onResult(list, firstLoadPosition, firstLoadSize)
}
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<Contact>) {
val list = contentResolver.query(
ContactsContract.Contacts.CONTENT_URI,
CONTACT_PROJECTION,
null,
null,
"${CONTACT_PROJECTION[2]} ASC LIMIT ${params.loadSize} OFFSET ${params.startPosition}"
)?.use {
getRows(it)
}!!
callback.onResult(list)
}
private fun getRowsNumbers() = contentResolver.query(
ContactsContract.Contacts.CONTENT_URI,
arrayOf(BaseColumns._ID),
null,
null,
null
)?.use {
it.count
} ?: 0
private fun getRows(cursor: Cursor) = arrayListOf<Contact>().apply {
cursor.apply {
while (moveToNext()) {
val id = getLong(getColumnIndex(CONTACT_PROJECTION[0]))
add(
Contact(
id,
ContactsContract.Contacts.getLookupUri(
id,
getString(getColumnIndex(CONTACT_PROJECTION[1]))
),
getString(getColumnIndex(CONTACT_PROJECTION[2])),
getString(getColumnIndex(CONTACT_PROJECTION[3]))?.toUri()
)
)
}
}
}.toList()
companion object {
private val CONTACT_PROJECTION = arrayOf(
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI
)
}
}
DataSourceFactory:
class ContactsDataSourceFactory(private val contentResolver: ContentResolver) :
DataSource.Factory<Int, Contact>() {
override fun create(): DataSource<Int, Contact> {
return ContactsDataSource(contentResolver)
}
}
ViewModel:
class ContactsViewModel(app: Application) : AndroidViewModel(app) {
lateinit var currentDataSource: PagingSource<Int, Contact>
val contacts = Pager(
PagingConfig(
pageSize = 20
)
) {
ContactsDataSourceFactory(app.contentResolver).asPagingSourceFactory().invoke().also {
currentDataSource = it
}
}
.flow
.cachedIn(viewModelScope)
}
RecyclerView Adapter:
private val CONTACT_DIFF_UTIL = object : DiffUtil.ItemCallback<Contact>() {
override fun areItemsTheSame(oldItem: Contact, newItem: Contact): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Contact, newItem: Contact): Boolean =
oldItem == newItem
}
class ContactsRvAdapter(private val onLongClick: () -> Unit) :
PagingDataAdapter<Contact, ContactsRvAdapter.Holder>(CONTACT_DIFF_UTIL) {
inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val ivContactPhoto = itemView.findViewById<ImageView>(R.id.ivContactPhoto)
private val tvContactName = itemView.findViewById<TextView>(R.id.tvContactName)
fun bind(contact: Contact?) {
contact ?: return
val photoUri = contact.photoUri
if (photoUri != null) {
ivContactPhoto.setImageURI(photoUri)
} else {
ivContactPhoto.setImageResource(R.drawable.ic_baseline_account_circle_60)
}
tvContactName.text = contact.name
itemView.setOnLongClickListener {
onLongClick()
return#setOnLongClickListener true
}
}
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bind(getItem(position))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.contacts_rv_row_item, parent, false)
return Holder(view)
}
}
Activity:
#ExperimentalCoroutinesApi
class MainActivity : AppCompatActivity() {
private val contactsViewModel: ContactsViewModel by viewModels()
private val contactsRvAdapter = ContactsRvAdapter {
contactsViewModel.currentDataSource.invalidate()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<RecyclerView>(R.id.rvContacts).apply {
adapter = contactsRvAdapter
addItemDecoration(
DividerItemDecoration(
this#MainActivity,
DividerItemDecoration.VERTICAL
)
)
}
lifecycleScope.launch {
contactsViewModel.contacts.collectLatest {
contactsRvAdapter.submitData(it)
}
}
}
}
I read generated code by room database and source code of LimitOffsetDataSource class and tried to follow the exact steps to build my own data source. Am I missing something? Any help or solution is appreciated.

Recyclerview not updating with changes in medialibrary

I have a code to retrieve list of all music from storage but after i renamed a file the recyclerview doesnt update with the change
even after deleting a file it still remains the same
fun Context.musicFiles():MutableList{
val list:MutableList<Music> = mutableListOf()
val uri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
//val uri: Uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI
// IS_MUSIC : Non-zero if the audio file is music
val selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0"
// Sort the musics
val sortOrder = MediaStore.Audio.Media.TITLE + " ASC"
//val sortOrder = MediaStore.Audio.Media.TITLE + " DESC"
// Query the external storage for music files
val cursor: Cursor = this.contentResolver.query(
uri, // Uri
null, // Projection
selection, // Selection
null, // Selection arguments
sortOrder // Sort order
)
// If query result is not empty
if (cursor!= null && cursor.moveToFirst()){
val id:Int = cursor.getColumnIndex(MediaStore.Audio.Media._ID)
val title:Int = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)
val artist:Int= cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)
val musicpathh:Int= cursor.getColumnIndex(MediaStore.Audio.Media.DATA)
val album:Int = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)
// Now loop through the music files
do {
val audioId:Long = cursor.getLong(id)
val audioTitle:String = cursor.getString(title)
val audioArtist:String = cursor.getString(artist)
val audiopath:String = cursor.getString(musicpathh)
val audioalbum:String = cursor.getString(album)
// Add the current music to the list
list.add(Music(audioId,audioTitle,audioArtist,audiopath,audioalbum))
}while (cursor.moveToNext())
}
// Finally, return the music files list
return list
}
data class Music(val id:Long, val title:String, val artist:String, val audiopath:String, val audioalbumm:String)
Function to get musicfiles
val list:MutableList = musicFiles()
val titles = mutableListOf<String>()
val artist = mutableListOf<String>()
val musicpath = mutableListOf<String>()
val album = mutableListOf<String>()
val checkd = mutableListOf<Boolean>()
for (music in list){titles.add(music.title)}
for (music in list){artist.add(music.artist)}
for (music in list){musicpath.add(music.audiopath)}
for (music in list){album.add(music.audioalbumm)}
for (music in list){checkd.add(false)}
val adapter= HobbiesAdapter(this, titles, artist, musicpath, album, checkd)
recyclerView.adapter = adapter
adapter
class HobbiesAdapter(val context: Context, val hobbies: MutableList, val artis: MutableList, val pathh: MutableList, val albumm: MutableList, val checkd: MutableList) : RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return hobbies.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val hobby = hobbies[position]
val artistt = artis[position]
val patth = pathh[position]
val albbum = albumm[position]
holder.setData(hobby, artistt, patth, position, albbum)
}
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var currentHobby: String = ""
var currentArtist: String = ""
var currentPath: String = ""
var currentAlbum: String = ""
var currentPosition: Int = 0
var checkdd:Int=0
var currentCheckedStatus:Boolean=false
init {
itemView.setOnClickListener {
if(itemView.checkstatus.isChecked==true){
itemView.checkstatus.isChecked=false
checkdd=adapterPosition
checkd.set(checkdd,false)
}
else{
itemView.checkstatus.isChecked=true
checkdd=adapterPosition
checkd.set(checkdd,true)
}
}
itemView.checkstatus.setOnClickListener {
if(itemView.checkstatus.isChecked==true){
itemView.checkstatus.isChecked=false
checkdd=adapterPosition
checkd.set(checkdd,false)
}
else{
itemView.checkstatus.isChecked=true
checkdd=adapterPosition
checkd.set(checkdd,true)
}
}
}
fun setData(hobby: String, artiist: String, paath: String, pos: Int, albuum: String) {
itemView.txvTitle.text = hobby
itemView.txvArtist.text=artiist
itemView.txvPath.text=paath
itemView.txvAlbum.text=albuum
itemView.checkstatus.isChecked=checkd.get(pos)
this.currentHobby = hobby
this.currentArtist = artiist
this.currentPath = paath
this.currentAlbum = albuum
this.currentPosition = pos
this.currentCheckedStatus=checkd.get(pos)
}
}
}

Read contacts and display it in a recyclerview in Kotlin

I am trying to read contacts from ContactsContract in Kotin. But it's not showing any of the contact in the recyclerview. The noticeable thing is that the java version of this code is working fine.
So, I here is my Kotlin code for reading the contact:
private var adapter: ContactsAdapter? = null
private var myContacts : MutableList<MyContacts> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// code for recyclerview and adapter and checkPermission
val itemDecoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.addItemDecoration(itemDecoration)
adapter = ContactsAdapter(myContacts)
recycler_view.hasFixedSize()
recycler_view.adapter = ContactsAdapter(myContacts)
checkPermission()
}
private fun loadContactFromProvider() {
showProgressBar()
val contentResolver = contentResolver
val cursor = contentResolver.query(CONTENT_URI, null, null, null, DISPLAY_NAME)
if (cursor != null && cursor.count > 0) {
while (cursor.moveToNext()) {
val id = cursor.getString(cursor.getColumnIndex(ID))
val name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME))
val hasPhoneNumber = cursor.getInt(cursor.getColumnIndex(HAS_PHONE_NUMBER))
val contacts = MyContacts()
if (hasPhoneNumber > 0) {
contacts.contactName = name
val phoneCursor = contentResolver.query(PHONE_URI, arrayOf(NUMBER), "$PHONE_ID = ?", arrayOf(id), null)
val phoneNumbers = ArrayList<String>()
phoneCursor!!.moveToFirst()
while (!phoneCursor.isAfterLast) {
val phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER)).replace(" ", "")
phoneNumbers.add(phoneNumber)
phoneCursor.moveToNext()
}
contacts.contactNumber = phoneNumbers
phoneCursor.close()
}
val inputStream = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, ContentUris.withAppendedId(CONTENT_URI, id.toLong()))
if (inputStream != null) {
val bitmap = BitmapFactory.decodeStream(inputStream)
contacts.contactImage = bitmap?.toString()
} else {
contacts.contactImage = vectorDrawableToBitmap(R.drawable.ic_person)?.toString()
}
log(contacts.contactName + " " + contacts.contactNumber.toString() + " " + contacts.contactImage.toString())
myContacts.add(contacts)
}
adapter?.notifyDataSetChanged()
cursor.close()
}
}
The log details are also fine, they are showing the full contact list. But I am unable to see it in the recyclerview. The constant field like ID, DISPLAY_NAME etc. are already defined in the companion object.
Kotlin code for RecyclerViewAdapter is:
class ContactsAdapter(private val contactList: MutableList<MyContacts>): RecyclerView.Adapter<ContactsAdapter.ContactViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ContactViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.contact_item_layout,viewGroup,false)
return ContactViewHolder(view)
}
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
val contact = contactList[position]
holder.name!!.text = contact.contactName
holder.mobile!!.text = contact.contactNumber[0]
Glide.with(holder.itemView.context)
.load(contact.contactImage)
.into(holder.image)
}
override fun getItemCount(): Int = contactList.size
class ContactViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
var image : ImageView = itemView.find(R.id.contact_image) as ImageView
var name : TextView? = itemView.find(R.id.contact_name) as TextView
var mobile : TextView? = itemView.find(R.id.contact_mobile) as TextView
}
}
Any help would be appreciated.
Thankyou

Categories

Resources