Как устранить сбой при открытии приложения рецептов после реализации Retrofit?Android

Форум для тех, кто программирует под Android
Anonymous
Как устранить сбой при открытии приложения рецептов после реализации Retrofit?

Сообщение Anonymous »

Я создал приложение с использованием API (https://www.themealdb.com/api/json/v1/1/categories.php), оно продолжает зависать, я проверил журнал, спросил в чате gpt, он говорит, что метод показать не нашел ошибку, которую не могу решить. Помогите мне ее решить

Код: Выделить всё

package com.example.therecipeapp

import retrofit2.Retrofit
import retrofit2.create
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

private val retrofit = Retrofit.Builder().baseUrl("https://www.themealdb.com/api/json/v1/1/")
.addConverterFactory(GsonConverterFactory.create()).build()

val recipeService = retrofit.create(ApiService::class.java)

interface ApiService{
@GET("categories.php")
suspend fun getCategories():CategoriesResponse
}
//Категории

Код: Выделить всё

package com.example.therecipeapp

data class Category(val idCategory:String ,
val strCategory:String,
val strCategoryThumb:String)
//"idCategory": "1",
//"strCategory": "Beef",
//"strCategoryThumb":

data class CategoriesResponse(val categories:List)
Основное действие

Код: Выделить всё

package com.example.therecipeapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.therecipeapp.ui.theme.TheRecipeAppTheme

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TheRecipeAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
RecipeScreen()
}
}
}
}
}

//Модель основного вида

Код: Выделить всё

package com.example.therecipeapp

import androidx.lifecycle.ViewModel
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.State;
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {

private val _categoriesState = mutableStateOf(RecipeState())
val categoriesState: State = _categoriesState

init {
fetchCategories()
}

private fun fetchCategories() {
viewModelScope.launch {
try {
val response = recipeService.getCategories()
_categoriesState.value = _categoriesState.value.copy(
list = response.categories,
loading = false,
error = null
)
} catch (e: Exception) {
_categoriesState.value = _categoriesState.value.copy(
loading = false,
error = "Error fetching Categoris ${e.message}"
)
}
}
}

data class RecipeState(
val loading: Boolean = true,
val list: List  = emptyList(),
val error: String? = null

)
}
//Экран рецептов

Код: Выделить всё

package com.example.therecipeapp

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
//import androidx.compose.ui.input.pointer.PointerIcon.Companion.Text
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.rememberAsyncImagePainter

@Composable
fun RecipeScreen(modifier: Modifier = Modifier){
val recipeViewModel: MainViewModel = viewModel()
val viewState by recipeViewModel.categoriesState
Box(modifier = Modifier.fillMaxSize()) {
when{
viewState.loading -> {
CircularProgressIndicator(modifier.align(Alignment.Center))
}
viewState.error != null->{
Text("Error Occurred")
}
else ->{
CategoriesScreen(categories = viewState.list)
}
}
}
}

@Composable
fun CategoriesScreen(categories :List) {
LazyVerticalGrid(GridCells.Fixed(2),modifier = Modifier.fillMaxSize()) {
items(categories){
category ->  CategoryItems(category = category)

}
}
}

//How Each Items looks Like
@Composable
fun CategoryItems(category :Category) {
Column(modifier = Modifier
.padding(8.dp)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally)
{
Image(
painter = rememberAsyncImagePainter(category.strCategoryThumb),
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.aspectRatio(1f)
)
Text(
text = category.strCategory,
color = Color.Black,
style = TextStyle(fontWeight=FontWeight.Bold),
modifier = Modifier.padding(top=4.dp)
)
}
}
Я новичок в разработке приложений, пожалуйста, помогите
Я пытался создать приложение для Android с использованием Kotlin и API, но оно вылетает каждый раз, когда я его запускаю.

Подробнее здесь: https://stackoverflow.com/questions/790 ... ing-retrof

Вернуться в «Android»