Skip to main content
se añadieron 146 caracteres en el cuerpo
Origen Enlace
Danxz
  • 39
  • 6

La llamada al metodo para que traiga la lista y la cargue en el recyclerview se lleva a cabo en el metodo "onCreateView" del fragment. Y aqui viene el problema... Cada vez que salgo y entro a este fragment se carga de nuevo la lista en el recyclerview y se duplica. Esto ocurre cada vez que entro y salgo del fragment, por lo que la lista siempre esta añadiendo nuevas canciones duplicadas y se vuelve infinito.

La llamada al metodo para que traiga la lista y la cargue en el recyclerview se lleva a cabo en el metodo "onCreateView" del fragment. Y aqui viene el problema... Cada vez que salgo y entro a este fragment se carga de nuevo la lista en el recyclerview y se duplica.

La llamada al metodo para que traiga la lista y la cargue en el recyclerview se lleva a cabo en el metodo "onCreateView" del fragment. Y aqui viene el problema... Cada vez que salgo y entro a este fragment se carga de nuevo la lista en el recyclerview y se duplica. Esto ocurre cada vez que entro y salgo del fragment, por lo que la lista siempre esta añadiendo nuevas canciones duplicadas y se vuelve infinito.

Añadido de las clase CustomAdapter y el objeto LocalSongsProvider
Origen Enlace
Danxz
  • 39
  • 6

CustomAdapter->

class CustomAdapteSongList(
        val context: Context,
        val lifecycle: LifecycleOwner,
        val layout: Int,
) : RecyclerView.Adapter<CustomAdapteSongList.ViewHolder>() {

    private var ListSongs: List<Song> = emptyList()


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val viewlayout = layoutInflater.inflate(layout, parent, false)
        return ViewHolder(viewlayout, context)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val itemsong = ListSongs[position]

        holder.bind(itemsong, lifecycle)
    }

    override fun getItemCount(): Int {
        return ListSongs.size
    }

    internal fun setSongs(songs: List<Song>) {
        this.ListSongs = songs
        notifyDataSetChanged()
    }

    class ViewHolder(viewlayout: View, val context: Context) : RecyclerView.ViewHolder(viewlayout) {

        fun bind(dataitem: Song, lifecycle: LifecycleOwner) {
            // itemview es el item de diseño
            // al que hay que poner los datos del objeto dataItem
            itemView.findViewById<TextView>(R.id.title_song).text = dataitem.title
            itemView.findViewById<TextView>(R.id.artist_name).text = dataitem.artistName

            var song_artWork = Uri.parse("content://media/external/audio/albumart")
            song_artWork = ContentUris.withAppendedId(song_artWork, dataitem.id)


            val file = File(song_artWork.getPath())
            Picasso.get()
                    .load(file)
                    .error(R.drawable.ic_standard_image_song)
                    .into(itemView.findViewById<ImageView>(R.id.iv_image_song))

            itemView.tag = dataitem
        }
    }
}

LocalSongsProvider->

object LocalSongsProvider {

    private val allDeviceSongs = ArrayList<Song>()

    val projection = arrayOf(
            MediaStore.Audio.AudioColumns._ID,
            MediaStore.Audio.AudioColumns.TITLE,
            MediaStore.Audio.AudioColumns.TRACK,
            MediaStore.Audio.AudioColumns.YEAR,
            MediaStore.Audio.AudioColumns.DURATION,
            MediaStore.Audio.AudioColumns.ALBUM,
            MediaStore.Audio.AudioColumns.ARTIST_ID,
            MediaStore.Audio.AudioColumns.ARTIST,
    )



    private fun getSongs(cursor: Cursor?): List<Song> {
        if (cursor != null) {
            // Cache column indices.
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
            val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)
            val trackColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TRACK)
            val yearColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.YEAR)
            val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
            val albumColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)
            val artistIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID)
            val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)

            while (cursor.moveToNext()) {
                // Get values of columns for a given video.
                val id = cursor.getLong(idColumn)
                val title = cursor.getString(titleColumn)
                val track = cursor.getInt(trackColumn)
                val year = cursor.getInt(yearColumn)
                val duration = cursor.getInt(durationColumn)
                val album = cursor.getString(albumColumn)
                val artistId = cursor.getInt(artistIdColumn)
                val artist = cursor.getString(artistColumn)

                val contentUri: Uri = ContentUris.withAppendedId(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        id
                )

                // Stores column values and the contentUri in a local object
                // that represents the media file.
                allDeviceSongs.add(Song(id, contentUri, title, track, year, duration, album, artistId, artist))
            }
        }
        return allDeviceSongs.reversed()
    }


        fun getAllDeviceSongs(context: Context): List<Song> {
            val cursor = BuildSongCursor(context)
            Log.d("lista", getSongs(cursor).toString())
            return getSongs(cursor)
        }


        private fun BuildSongCursor(context: Context): Cursor? {
            try {
                return context.contentResolver.query(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        projection,
                        null,
                        null,
                        null)
            } catch (e: SecurityException) {
                return null
            }
        }

    }

CustomAdapter->

class CustomAdapteSongList(
        val context: Context,
        val lifecycle: LifecycleOwner,
        val layout: Int,
) : RecyclerView.Adapter<CustomAdapteSongList.ViewHolder>() {

    private var ListSongs: List<Song> = emptyList()


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val viewlayout = layoutInflater.inflate(layout, parent, false)
        return ViewHolder(viewlayout, context)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val itemsong = ListSongs[position]

        holder.bind(itemsong, lifecycle)
    }

    override fun getItemCount(): Int {
        return ListSongs.size
    }

    internal fun setSongs(songs: List<Song>) {
        this.ListSongs = songs
        notifyDataSetChanged()
    }

    class ViewHolder(viewlayout: View, val context: Context) : RecyclerView.ViewHolder(viewlayout) {

        fun bind(dataitem: Song, lifecycle: LifecycleOwner) {
            // itemview es el item de diseño
            // al que hay que poner los datos del objeto dataItem
            itemView.findViewById<TextView>(R.id.title_song).text = dataitem.title
            itemView.findViewById<TextView>(R.id.artist_name).text = dataitem.artistName

            var song_artWork = Uri.parse("content://media/external/audio/albumart")
            song_artWork = ContentUris.withAppendedId(song_artWork, dataitem.id)


            val file = File(song_artWork.getPath())
            Picasso.get()
                    .load(file)
                    .error(R.drawable.ic_standard_image_song)
                    .into(itemView.findViewById<ImageView>(R.id.iv_image_song))

            itemView.tag = dataitem
        }
    }
}

LocalSongsProvider->

object LocalSongsProvider {

    private val allDeviceSongs = ArrayList<Song>()

    val projection = arrayOf(
            MediaStore.Audio.AudioColumns._ID,
            MediaStore.Audio.AudioColumns.TITLE,
            MediaStore.Audio.AudioColumns.TRACK,
            MediaStore.Audio.AudioColumns.YEAR,
            MediaStore.Audio.AudioColumns.DURATION,
            MediaStore.Audio.AudioColumns.ALBUM,
            MediaStore.Audio.AudioColumns.ARTIST_ID,
            MediaStore.Audio.AudioColumns.ARTIST,
    )



    private fun getSongs(cursor: Cursor?): List<Song> {
        if (cursor != null) {
            // Cache column indices.
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
            val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)
            val trackColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TRACK)
            val yearColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.YEAR)
            val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
            val albumColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)
            val artistIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID)
            val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)

            while (cursor.moveToNext()) {
                // Get values of columns for a given video.
                val id = cursor.getLong(idColumn)
                val title = cursor.getString(titleColumn)
                val track = cursor.getInt(trackColumn)
                val year = cursor.getInt(yearColumn)
                val duration = cursor.getInt(durationColumn)
                val album = cursor.getString(albumColumn)
                val artistId = cursor.getInt(artistIdColumn)
                val artist = cursor.getString(artistColumn)

                val contentUri: Uri = ContentUris.withAppendedId(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        id
                )

                // Stores column values and the contentUri in a local object
                // that represents the media file.
                allDeviceSongs.add(Song(id, contentUri, title, track, year, duration, album, artistId, artist))
            }
        }
        return allDeviceSongs.reversed()
    }


        fun getAllDeviceSongs(context: Context): List<Song> {
            val cursor = BuildSongCursor(context)
            Log.d("lista", getSongs(cursor).toString())
            return getSongs(cursor)
        }


        private fun BuildSongCursor(context: Context): Cursor? {
            try {
                return context.contentResolver.query(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        projection,
                        null,
                        null,
                        null)
            } catch (e: SecurityException) {
                return null
            }
        }

    }

se eliminaron 327 caracteres en el cuerpo
Origen Enlace
Danxz
  • 39
  • 6
class SongListFragment : Fragment(), SearchView.OnQueryTextListener {

    private lateinit var songsListViewModel: SongListViewModel
    private lateinit var rootView: View 


    override fun <I : Any?, O : Any?> registerForActivityResult(
            contract: ActivityResultContract<I, O>,
            callback: ActivityResultCallback<O>
    ): ActivityResultLauncher<I> {
        TODO("Not yet implemented")
    }

    override fun <I : Any?, O : Any?> registerForActivityResult(
            contract: ActivityResultContract<I, O>,
            registry: ActivityResultRegistry,
            callback: ActivityResultCallback<O>
    ): ActivityResultLauncher<I> {
        TODO("Not yet implemented")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        init()
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        Log.d("onCreateView", "onCreateView")
        rootView = inflater.inflate(R.layout.fragment_songlist, container, false)

        init()

        (activity as AppCompatActivity?)!!.setSupportActionBar(rootView.findViewById(R.id.toolbar))
        return rootView
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    override fun onQueryTextSubmit(query: String?): Boolean {
        TODO("Not yet implemented")
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        TODO("Not yet implemented")
    }


    private fun init(){
        songsListViewModel = ViewModelProvider(this).get(SongListViewModel::class.java)
        songsListViewModel.SongListViewModel(rootView, this)
        songsListViewModel.showAllDeviceSongs()

/*        //observador -> observa la variable MutableLiveData<List<Song>> de el viewModel, para que cuando cambie actualice la lista
        songsListViewModel.getSongsList().observe(viewLifecycleOwner, Observer { it ->
            it?.let {
                songsListViewModel.showAllDeviceSongs()
            }
        })*/
    }


}
class SongListFragment : Fragment(), SearchView.OnQueryTextListener {

    private lateinit var songsListViewModel: SongListViewModel
    private lateinit var rootView: View

    override fun <I : Any?, O : Any?> registerForActivityResult(
            contract: ActivityResultContract<I, O>,
            callback: ActivityResultCallback<O>
    ): ActivityResultLauncher<I> {
        TODO("Not yet implemented")
    }

    override fun <I : Any?, O : Any?> registerForActivityResult(
            contract: ActivityResultContract<I, O>,
            registry: ActivityResultRegistry,
            callback: ActivityResultCallback<O>
    ): ActivityResultLauncher<I> {
        TODO("Not yet implemented")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        init()
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        Log.d("onCreateView", "onCreateView")
        rootView = inflater.inflate(R.layout.fragment_songlist, container, false)

        (activity as AppCompatActivity?)!!.setSupportActionBar(rootView.findViewById(R.id.toolbar))
        return rootView
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    override fun onQueryTextSubmit(query: String?): Boolean {
        TODO("Not yet implemented")
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        TODO("Not yet implemented")
    }


    private fun init(){
        songsListViewModel = ViewModelProvider(this).get(SongListViewModel::class.java)
        songsListViewModel.SongListViewModel(rootView, this)
        songsListViewModel.showAllDeviceSongs()

/*        //observador -> observa la variable MutableLiveData<List<Song>> de el viewModel, para que cuando cambie actualice la lista
        songsListViewModel.getSongsList().observe(viewLifecycleOwner, Observer { it ->
            it?.let {
                songsListViewModel.showAllDeviceSongs()
            }
        })*/
    }


}
class SongListFragment : Fragment(), SearchView.OnQueryTextListener {

    private lateinit var songsListViewModel: SongListViewModel
    private lateinit var rootView: View 


    override fun <I : Any?, O : Any?> registerForActivityResult(
            contract: ActivityResultContract<I, O>,
            callback: ActivityResultCallback<O>
    ): ActivityResultLauncher<I> {
        TODO("Not yet implemented")
    }

    override fun <I : Any?, O : Any?> registerForActivityResult(
            contract: ActivityResultContract<I, O>,
            registry: ActivityResultRegistry,
            callback: ActivityResultCallback<O>
    ): ActivityResultLauncher<I> {
        TODO("Not yet implemented")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        Log.d("onCreateView", "onCreateView")
        rootView = inflater.inflate(R.layout.fragment_songlist, container, false)

        init()

        (activity as AppCompatActivity?)!!.setSupportActionBar(rootView.findViewById(R.id.toolbar))
        return rootView
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    override fun onQueryTextSubmit(query: String?): Boolean {
        TODO("Not yet implemented")
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        TODO("Not yet implemented")
    }


    private fun init(){
        songsListViewModel = ViewModelProvider(this).get(SongListViewModel::class.java)
        songsListViewModel.SongListViewModel(rootView, this)
        songsListViewModel.showAllDeviceSongs()

    }


}
Origen Enlace
Danxz
  • 39
  • 6
Loading