Home > Blockchain >  Why can't I format the duration of the audio file into a textView?
Why can't I format the duration of the audio file into a textView?

Time:03-31

I'm trying to format the duration time of the song, because I receive it in milliseconds, but the way I'm trying is not working.

I tried to use this way, the commented line (//) is when I receive the duration, but in milliseconds.

This song_duration is a String var from a model class, and song_time, is the id for the textView in the xml file.

In String.toLong(), I get the error on the image

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.song_title.text = songList[position].song_title
            holder.song_artist.text = songList[position].artist
        //    holder.song_time.text = songList[position].song_duration

            holder.song_time.text = songList[position].song_duration.format(
                    "%d:d",
                        TimeUnit.MILLISECONDS.toMinutes(String.toLong()),
                        TimeUnit.MILLISECONDS.toSeconds(String.toLong())-
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(String.toLong()))
            )
        
        var bitmap : Bitmap? = null
        try {
            bitmap =
                MediaStore.Images.Media.getBitmap(context.contentResolver, songList[position].image)
            holder.song_image.setImageBitmap(bitmap)
        }catch (e: Exception){

        }
        holder.itemView.setOnClickListener{
            currentSong = position
            onSongSelect.onSelect(songList[position])
        }
    } 

CodePudding user response:

You are passing invalid parameter's to TimeUnit.MILLISECONDS.toMinutes. To get formatted time from Millis you can use the code below

In your onBindViewHolder change from

holder.song_time.text = songList[position].song_duration.format(
                    "%d:d",
                        TimeUnit.MILLISECONDS.toMinutes(String.toLong()),
                        TimeUnit.MILLISECONDS.toSeconds(String.toLong())-
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(String.toLong()))
            )

To

holder.song_time.text = getformattedTime(songList[position].song_duration.toLong())

Then Add the function to format time for you

public String getformattedTime(long seconds) {
    long sec = seconds % 60;
    long min = (seconds / 60) % 60;
    long hr = (seconds / (60 * 60)) % 24;
    return String.format("%d:d:d", hr, min, sec);
}
  • Related