interface DeezerApiService {
@GET("genre?output=json") // json endpoint instead of “/”
suspend fun getGenres(): GenreResponse
@GET("genre/{genre_id}/artists")
suspend fun getArtists(@Path("genre_id") genreId: Int): ArtistResponse
@GET("artist/{artist_id}")
suspend fun getArtistDetail(@Path("artist_id") artistId: Int): ArtistDetailResponse
@GET("artist/{artist_id}/albums")
suspend fun getArtistAlbums(@Path("artist_id") artistId: Int): AlbumResponse
data class AlbumResponse(val data: List<Album>) {
fun toAlbumList(): List<Album> {
return data.map { albumData ->
Album(
id = albumData.id,
title = albumData.title,
link = albumData.link,
cover = albumData.cover,
cover_small = albumData.cover_small,
cover_medium = albumData.cover_medium,
cover_big = albumData.cover_big,
cover_xl = albumData.cover_xl,
release_date = albumData.release_date,
tracklist = albumData.tracklist,
type = albumData.type
)
}
}
}
@GET("album/{album_id}")
suspend fun getAlbumDetails(@Path("album_id") albumId: Int): AlbumDetailResponse
data class AlbumDetailResponse(
val id: Int,
val title: String,
val cover_medium: String,
val tracks: TracksResponse
)
data class TracksResponse(
val data: List<Song>,
val inherit_album_cover_medium: String // Add the inheritance field
)
// Create a new class for storing response fields.
data class GenreResponse(val data: List<Category>)
data class ArtistResponse(val data: List<Artist>)
data class ArtistDetailResponse(val id: Int, val name: String, val picture_big: String, val albums: List<Album>?)
companion object {
private const val BASE_URL = "https://api.deezer.com/"
fun create(): DeezerApiService {
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.build()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(DeezerApiService::class.java)
}
}
class DeezerRepository {
private val deezerApiService = DeezerApiService.create()
suspend fun getCategories(): List<Category> {
val response = deezerApiService.getGenres()
return response.data.map { category ->
Category(category.id, category.name, category.picture_medium)
}
}
suspend fun getArtists(genreId: Int): List<Artist> {
val response = deezerApiService.getArtists(genreId)
return response.data
}
suspend fun getArtistDetail(artistId: Int): ArtistDetail {
val response = deezerApiService.getArtistDetail(artistId)
return ArtistDetail(
id = response.id,
name = response.name,
pictureBig = response.picture_big,
albums = response.albums
)
}
suspend fun getArtistAlbums(artistId: Int): List<Album> {
val response = deezerApiService.getArtistAlbums(artistId)
return response.toAlbumList()
}
suspend fun getAlbumDetails(albumId: Int): AlbumDetails {
val response = deezerApiService.getAlbumDetails(albumId)
return AlbumDetails(
id = response.id,
title = response.title,
cover_medium = response.cover_medium,
songs = response.tracks.data
)
}
Assistant
User
In the code when i preview a song and then leave the page . Song preview keeps going even if i closed the page can you fix it
Assistant
I assume you want to stop playing the song when you navigate away from the AlbumDetailScreen. To do this, you can use the DisposableEffect function in your AlbumDetailScreen composable. It allows you to perform some action when the composable is disposed, which happens when you navigate away from the screen.
Here's an updated version of the AlbumDetailScreen with the DisposableEffect:
@
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
data class Album(
val id: Int,
val title: String,
val link: String,
val cover: String,
val cover_small: String,
val cover_medium: String,
val cover_big: String,
val cover_xl: String,
val release_date: String,
val tracklist: String,
val type: String
),package com.example.musicapp.Data
data class AlbumDetails(
val id: Int,
val title: String,
val cover_medium: String,
val songs: List
),package com.example.musicapp.Data
data class Artist(
val id: Int,
val name: String,
val picture_medium: String
),package com.example.musicapp.Data
data class ArtistDetail(
val id: Int,
val name: String,
val pictureBig: String,
val albums: List?,
),package com.example.musicapp.Data
data class Category(
val id: Int,
val name: String,
val picture_medium: String
),package com.example.musicapp.Data
data class Song(
val id: Int,
val title: String,
val duration: Int, // in seconds
val album: Album,
val cover_medium: String,
val preview: String // 30 seconds preview URL
),package com.example.musicapp.Interface
if (it.albums.isNullOrEmpty()) {
Log.d("ArtistDetailScreen", "No albums found for artist ${it.name}")
}
LazyColumn {
items(it.albums ?: emptyList()) { album ->
ArtistDetailItem(album)
}
}
}
}
}
}
*/
@Composable
fun ArtistDetailScreen(artistId: Int,navController: NavController) {
val artistsViewModel: ArtistsViewModel = viewModel()
artistsViewModel.fetchArtistDetails(artistId)
val artistDetails by artistsViewModel.artistDetails.collectAsState()
artistDetails?.let { details ->
val artistDetail = details.firstOrNull()
artistDetail?.let {
Scaffold(
topBar = {
TopBar(title = it.name)
},
content = { padding ->
Column(modifier = Modifier.padding(padding)) {
val painter = rememberAsyncImagePainter(model = it.pictureBig)
Image(
painter = painter,
contentDescription = it.name,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.fillMaxWidth(0.5f) // Change this line to set the image width to half
.padding(horizontal = 16.dp)
.align(Alignment.CenterHorizontally) // Center the image horizontally
)
if (it.albums.isNullOrEmpty()) {
Log.d("ArtistDetailScreen", "No albums found for artist ${it.name}")
}
LazyColumn {
items(it.albums ?: emptyList()) { album ->
ArtistDetailItem(album, navController) // Pass the navController to ArtistDetailItem
}
}
}
}
)
}
}
}
@Composable
fun ArtistDetailItem(album: Album, navController: NavController, // Add the navController parameter
) {
Row(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.background(
color = Color.Black.copy(alpha = 0.5f), // Change the alpha value here
shape = RoundedCornerShape(8.dp)
)
.border( // Add this line to draw an outline around the item
width = 1.dp,
color = Color.LightGray,
shape = RoundedCornerShape(8.dp)
)
.clickable(onClick = { navController.navigate("albumDetail/${album.id}") }) // Add this line for navigation
@Composable
fun ArtistsScreen(navController: NavController, categoryId: Int) {
val categoriesViewModel: CategoriesViewModel = viewModel()
val allCategories by categoriesViewModel.categories.collectAsState()
val category = allCategories.firstOrNull { it.id == categoryId }
val artistsViewModel: ArtistsViewModel = viewModel()
val artists by artistsViewModel.artists.collectAsState()
artistsViewModel.fetchArtists(categoryId)
if (category != null) {
Scaffold(
topBar = { TopBar(title = category.name) },
content = { padding ->
Column(modifier = Modifier.padding(padding)) {
ArtistsScreenContent(
genre = category,
artists = artists,
onArtistSelected = { artist -> // FIX HERE
navController.navigate("artistDetail/${artist.id}")
}
)
}
}
)
} else {
Text("Category not found")
}
}
@Composable
fun ArtistsScreenContent(
genre: Category,
artists: List,
onArtistSelected: (Artist) -> Unit = {},
) {
Column {
Text(
text = "Genre Artists:${genre.name}",
style = MaterialTheme.typography.h6,
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp)
)
@Composable
fun FavoritesScreen(navController: NavController) {
val context = LocalContext.current
val playerViewModel = remember { PlayerViewModel(context) }
val favorites by playerViewModel.favorites.collectAsState(emptyList())
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MusicAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
MainScreen()
}
}
}
}
}
@Composable
fun FirstScreen(modifier: Modifier = Modifier) {
val categoriesViewModel: CategoriesViewModel = viewModel()
val categories by categoriesViewModel.categories.collectAsState()
Scaffold(
content = { padding ->
Column(
modifier = modifier.padding(padding)
) {
// Add your UI components here
MusicCategoriesScreen(categories = categories, topBar = { TopBar(title = "Music Categories") })
}
}
)
}
@Composable
fun SecondScreen(modifier: Modifier = Modifier) {
Scaffold(
topBar = {
// No top bar title
},
content = { padding ->
Column(
modifier = modifier.padding(padding)
) {
Text(text = "This is the second screen")
}
}
)
}
@Composable
fun MainScreen() {
val navController = rememberNavController()
val localViewModelStoreOwner = LocalViewModelStoreOwner.current
@Composable
fun BottomNavigationBar(navController: NavController) {
val navBackStackEntry = navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry.value?.destination?.route
class PlayerViewModel(private val context: Context) : ViewModel() {
var currentPlayer = mutableStateOf<SimpleExoPlayer?>(null)
var currentSong = mutableStateOf<Song?>(null)
var isPlaying = mutableStateOf(false)
private val sharedPreferences = context.getSharedPreferences("music_app", Context.MODE_PRIVATE)
private val gson = Gson()
private val _favorites = MutableStateFlow<List<Song>>(emptyList())
val favorites: StateFlow<List<Song>> = _favorites.asStateFlow()
fun createExoPlayer(context: Context): SimpleExoPlayer {
return SimpleExoPlayer.Builder(context).build()
}
fun playSong(context: Context, song: Song) {
currentPlayer.value?.let {
if (currentSong.value?.id == song.id) {
if (isPlaying.value) {
pauseSong()
} else {
resumeSong()
}
return
} else {
it.pause()
it.release()
}
}
currentSong.value = song
val player = createExoPlayer(context)
player.setMediaItem(MediaItem.fromUri(song.preview))
player.prepare()
player.play()
isPlaying.value = true
currentPlayer.value = player
}
fun pauseSong() {
currentPlayer.value?.pause()
isPlaying.value = false
}
fun resumeSong() {
currentPlayer.value?.play()
isPlaying.value = true
}
override fun onCleared() {
super.onCleared()
currentPlayer.value?.release()
}
// Add a private function to load favorites from SharedPreferences
private fun loadFavorites(): List<Song> {
val json = sharedPreferences.getString("favorites", "[]") ?: "[]"
val type = object : TypeToken<List<Song>>() {}.type
return gson.fromJson(json, type)
}
// Save favorites to SharedPreferences
private fun saveFavorites() {
sharedPreferences.edit().putString("favorites", gson.toJson(_favorites.value)).apply()
}
// Update addFavoriteSong and removeFavoriteSong functions to save favorites after making changes
fun addFavoriteSong(song: Song) {
_favorites.value = _favorites.value.toMutableList().apply { add(song) }
saveFavorites()
}
fun removeFavoriteSong(song: Song) {
_favorites.value = _favorites.value.toMutableList().apply { remove(song) }
saveFavorites()
}
fun isFavorite(song: Song): Boolean {
return _favorites.value.contains(song)
}
} -> These are my classes separated with ",". I have a problem. Problem is favorites feature does not work correctly. When user clicks empty heart icon on album detail item composable. The heart icon should turn to a full heart immediatly but it is only turning when i try to scroll the album detail items. Also i want to use local storage to save songs to favorites. When i try to add a song to favorites by clicking the heart icon on album detail item composable. After i navigate to the favorites screen from bottom bar. I don't see favorite songs. Help me to fix app's functionality as i described.
The immediate problem with the heart icon not changing is likely due to recomposition. The AlbumDetailItem composable function may not be automatically recomposing when the playerViewModel.favorites state changes. To fix this, you can explicitly declare a mutable state that observes the favorite status of a song and use it in your UI.
Here's an updated version of the AlbumDetailItem function, observe the "isFavoriteState" and "onCommit" blocks:
@Composable
fun AlbumDetailItem(song: Song, navController: NavController, playerViewModel: PlayerViewModel) {
val context = LocalContext.current
// Observe the favorite status of the song
val isFavoriteState = remember { mutableStateOf(playerViewModel.isFavorite(song)) }
// Watch for changes in the favorites and update the isFavoriteState appropriately
LaunchedEffect(playerViewModel.favorites) {
isFavoriteState.value = playerViewModel.isFavorite(song)
}
// Your previous code for Row, Column, etc.
IconButton(
onClick = {
if (playerViewModel.isFavorite(song)) {
playerViewModel.removeFavoriteSong(song)
} else {
playerViewModel.addFavoriteSong(song)
}
// Update isFavoriteState when heart icon is clicked
isFavoriteState.value = !isFavoriteState.value
},
modifier = Modifier
.align(Alignment.CenterVertically)
.padding(8.dp)
) {
Icon(
painter = painterResource(id = if (isFavoriteState.value) R.drawable.heart_full else R.drawable.heart_empty),
contentDescription = if (isFavoriteState.value) "Favorite" else "Not Favorite",
modifier = Modifier.size(24.dp)
)
}
}
As for the problem with saving and loading favorites, I see that you're using SharedPreferences for storage, and you have implemented the loadFavorites and saveFavorites functions in the PlayerViewModel. However, I don't see a place where you're actually loading the favorites at the initialization of the ViewModel. You should update the _favorites MutableStateFlow with the loaded favorites during ViewModel initialization.
Here's a change you should make to the PlayerViewModel to load the favorites during initialization:
class PlayerViewModel(private val context: Context) : ViewModel() {
// ...
init {
// Load favorites during ViewModel initialization
_favorites.value = loadFavorites()
}
// ...
}
With these changes, the heart icon should update immediately when clicked, and favorites should be properly loaded and displayed when navigating to the Favorites screen.