class PlayerViewModel(private val context: DeezerRepository) : 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)
}
Assistant
I would like to first recommend separating all classes into their own files because this will make your code base more organized and easier to maintain. Then, you can import them in the files they are being used. Once that is done, we can focus on fixing the specific errors you have mentioned.
Unresolved reference: getSharedPreferences in PlayerViewModel
To fix this error, you need to initialize the PlayerViewModel with a context. Then, you can use the context to access the getSharedPreferences method. Make sure to update the PlayerViewModel class declaration to accept the context parameter.
class PlayerViewModel(private val context: Context) : ViewModel() {
// ...
private val sharedPreferences = context.getSharedPreferences("music_app", Context.MODE_PRIVATE)
// ...
}
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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: PlayerViewModel = viewModel()
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
Image(
painter = painter,
contentDescription = category.name,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
Text(
text = category.name,
modifier = Modifier
.align(Alignment.BottomCenter)
.background(color = Color.Black.copy(alpha = 0.7f))
.fillMaxWidth()
.padding(4.dp),
style = MaterialTheme.typography.body2,
color = Color.White, // Change the text color to white
textAlign = TextAlign.Center
)
}
}
},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.Data
data class AlbumDetails(
val id: Int,
val title: String,
val cover_medium: String,
val songs: List
),package com.example.musicapp.Data
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
)-> these are some of my classes separated with "," . Errors -> at playerviewmodel ->Unresolved reference: getSharedPreferences:21,Overload resolution ambiguity:public open fun <T : Any!> fromJson(json: JsonElement!, typeOfT: Type!): TypeVariable(T)! defined in com.google.gson.Gsonpublic open fun <T : Any!> fromJson(reader: JsonReader!, typeOfT: Type!): TypeVariable(T)! defined in com.google.gson.Gsonpublic open fun <T : Any!> fromJson(json: Reader!, typeOfT: Type!): TypeVariable(T)! defined in com.google.gson.Gsonpublic open fun <T : Any!> fromJson(json: String!, typeOfT: Type!): TypeVariable(T)! defined in com.google.gson.Gson:74. Fix the errors and fix any issue u notice in the classes
Now, when you are initializing the PlayerViewModel in your Composables, pass in the LocalContext.current:
@Composable
fun AlbumDetailScreen(/* ... */) {
val context = LocalContext.current
// ...
val playerViewModel = remember { PlayerViewModel(context) }
// ...
}
Overload resolution ambiguity in Gson error in PlayerViewModel
To fix this, you need to specify a proper type token for the Gson calls. First, you need to import the TypeToken from the com.google.gson.reflect package.
import com.google.gson.reflect.TypeToken
Then, update the Gson calls as follows:
private fun loadFavorites(): List<Song> {
val json = sharedPreferences.getString("favorites", "[]") ?: "[]"
val type = object : TypeToken<List<Song>>() {}.type
return gson.fromJson(json, type)
}
After applying these changes, your code should work without errors. However, it is still recommended to separate each class into its own file.