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
)
// 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
This issue is possibly related to the view being disposed but still playing the song. I notice you've added the DisposableEffect in the AlbumDetailScreen to handle stopping the song, but you should also have it in the FavoritesScreen. Add the same DisposableEffect to your FavoritesScreen:
This should stop the song correctly when you navigate away from the screen, and your app should no longer crash when using the back button.
User
App just getting closed when i press back when i'm at favorites screen
Assistant
I see that you are using a Scaffold in both your AlbumDetailScreen and FavoritesScreen. When you navigate from AlbumDetailScreen to FavoritesScreen, the default back button behavior of Android will navigate to the previous activity or exit the application, irrespective of the navigation management within the MusicAppTheme.
To enable back navigation within MainScreen using the Android back button, you need to define a back press dispatcher within your MainActivity and handle the back press event with NavController.
First, add the OnBackPressedDispatcher and OnBackPressedDispatcherOwner imports to your MainActivity:
@Composable
fun AlbumDetailScreen(
albumId: Int
) {
val context = LocalContext.current
val deezerRepository = remember { DeezerRepository() } // memoize to avoid re-initialization
val albumDetailsViewModel: AlbumDetailsViewModel = viewModel()
// Replace the previous playerViewModel assignment with this code:
val playerViewModel = remember { PlayerViewModel(context) }
albumDetailsViewModel.fetchAlbumDetails(albumId)
val albumDetails = albumDetailsViewModel.albumDetails.collectAsState().value
albumDetails?.let { details ->
Scaffold(
topBar = {
TopBar(title = details.title)
},
content = { padding ->
Column(
modifier = Modifier.padding(padding)
) {
LazyColumn {
itemsIndexed(details.songs) { _, song -> // Use itemsIndexed instead of items
AlbumDetailItem(song, playerViewModel)
}
}
}
}
)
}
DisposableEffect(Unit) {
onDispose {
playerViewModel.stopSong() // Add a stopSong function to the PlayerViewModel, when page changes stop the song
}
}
}
@Composable
fun AlbumDetailItem(song: Song, 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)
}
Row(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.background(
color = Color.Black.copy(alpha = 0.5f),
shape = RoundedCornerShape(8.dp)
)
.border(
width = 1.dp,
color = Color.LightGray,
shape = RoundedCornerShape(8.dp)
)
) {
val painter = rememberImagePainter(
data = song.album.cover_medium,
builder = {
crossfade(true)
transformations(CircleCropTransformation())
}
)
@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(
artists = artists,
onArtistSelected = { artist -> // FIX HERE
navController.navigate("artistDetail/${artist.id}")
}
)
}
}
)
} else {
Text("Category not found")
}
}
@Composable
fun ArtistsScreenContent(
artists: List,
onArtistSelected: (Artist) -> Unit = {},
) {
Column {
@Composable
fun FavoritesScreen() {
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 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()
init {
// Load favorites during ViewModel initialization
_favorites.value = loadFavorites()
}
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
}
fun stopSong() {
currentPlayer.value?.stop()
isPlaying.value =false
}
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 some of my classes separated with",". I was at album detail item composable and then i opened favorites screen page. then i wanted to use back button of android . App closed , why ? I want to be able to use default back feature of android without having crashes in the app
In your MainActivityonCreate, set the backDispatcher:
override fun onCreate(savedInstanceState: Bundle?) {
super