Почему я не получаю данные от API?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Почему я не получаю данные от API?

Сообщение Anonymous »

У меня проблемы с пониманием, почему мой список рецептов не работает. Я пытаюсь использовать Spoonacular API для отображения списка рецептов, но я не получаю никаких данных от API. https://github.com/tasmiya92/recipesapp ... ctivity.kt. Однако в этом примере пользователь Tasmiya использовал деятельность для обработки логики API. Я хочу сохранить всю связанную с API логику в рамках моего рецепта. Я проверил компиляцию, и нет ошибок. От Google API Manager: < /p>
2025-04-25 11:53:21.648 24237-24476 GoogleApiManager com.example.smartfreezer E Failed to get service from broker.
java.lang.SecurityException: Unknown calling package name 'com.google.android.gms'.
at android.os.Parcel.createExceptionOrNull(Parcel.java:2456)
at android.os.Parcel.createException(Parcel.java:2440)
at android.os.Parcel.readException(Parcel.java:2423)
at android.os.Parcel.readException(Parcel.java:2365)
at aubj.a(:com.google.android.gms@251333029@25.13.33 (190400-745790146):36)
at atzq.z(:com.google.android.gms@251333029@25.13.33 (190400-745790146):143)
at atgz.run(:com.google.android.gms@251333029@25.13.33 (190400-745790146):42)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at cbvs.mk(:com.google.android.gms@251333029@25.13.33 (190400-745790146):1)
at cbvs.dispatchMessage(:com.google.android.gms@251333029@25.13.33 (190400-745790146):5)
at android.os.Looper.loopOnce(Looper.java:211)
at android.os.Looper.loop(Looper.java:300)
at android.os.HandlerThread.run(HandlerThread.java:67)
2025-04-25 11:53:23.882 24237-24237 Compatibil...geReporter com.example.smartfreezer D Compat change id reported: 150939131; UID 10447; state: ENABLED
< /code>
Основная проблема здесь: < /p>
class RecipesFragment : Fragment(R.layout.fragment_recipes) {

private lateinit var binding: FragmentRecipesBinding
private lateinit var recipesViewModel: RecipesViewModel
private val recipesAdapter by lazy { RecipesAdapter() }

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

binding = FragmentRecipesBinding.bind(view)

// Create a ViewModelFactory instance
val factory = RecipesViewModelFactory(requireActivity().application, foodRecipesApi)
recipesViewModel = ViewModelProvider(this,factory).get(RecipesViewModel::class.java)

// Setup RecyclerView
setupRecyclerView()

// Load recipes from the API
loadRecipes()
}

private fun setupRecyclerView() {
binding.recipesRecyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = recipesAdapter
}
}

private fun loadRecipes() {
recipesViewModel.getRecipes(recipesViewModel.applyQueries()) // Get the recipes from the API
recipesViewModel.recipesResponse.observe(viewLifecycleOwner, { response ->
when(response) {
is NetworkResult.Success -> {
binding.shimmerLayout.stopShimmer()
binding.shimmerLayout.visibility = View.GONE
response.data?.let { recipesAdapter.setData(response.data) }
}
is NetworkResult.Error -> {
binding.shimmerLayout.stopShimmer()
binding.shimmerLayout.visibility = View.GONE
// Handle the error, display a message, or whatever is necessary
}
is NetworkResult.Loading -> {
binding.shimmerLayout.startShimmer()
binding.shimmerLayout.visibility = View.VISIBLE
}
}
})
}
< /code>
пакет com.example.smartfreezer.viewmodels < /p>
import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.smartfreezer.api.FoodRecipesApi
import com.example.smartfreezer.models.FoodRecipe
import com.example.smartfreezer.models.Result
import com.example.smartfreezer.util.NetworkResult
import com.example.smartfreezer.util.Constants.Companion.API_KEY
import com.example.smartfreezer.util.Constants.Companion.QUERY_ADD_RECIPE_INFORMATION
import com.example.smartfreezer.util.Constants.Companion.QUERY_API_KEY
import com.example.smartfreezer.util.Constants.Companion.QUERY_DIET
import com.example.smartfreezer.util.Constants.Companion.QUERY_FILL_INGREDIENTS
import com.example.smartfreezer.util.Constants.Companion.QUERY_NUMBER
import com.example.smartfreezer.util.Constants.Companion.QUERY_TYPE
import kotlinx.coroutines.launch
import retrofit2.Response

class RecipesViewModel(
private val foodRecipesApi: FoodRecipesApi,
application: Application
) : AndroidViewModel(application) {

private val _recipesResponse = MutableLiveData()
val recipesResponse: LiveData get() = _recipesResponse

// API call to get the recipes
fun getRecipes(queries: Map) {
_recipesResponse.value = NetworkResult.Loading()

viewModelScope.launch {
if (hasInternetConnection()) {
try {
val response = foodRecipesApi.getRecipes(queries)
_recipesResponse.value = handleResponse(response)
} catch (e: Exception) {
_recipesResponse.value = NetworkResult.Error("Error: ${e.message}")
}
} else {
_recipesResponse.value = NetworkResult.Error("No Internet Connection")
}
}
}

// Handling API Responses
private fun handleResponse(response: Response): NetworkResult {
return if (response.isSuccessful) {
val data = response.body()?.results
if (data != null && data.isNotEmpty()) {
NetworkResult.Success(data)
} else {
NetworkResult.Error("Error: No data found")
}
} else {
NetworkResult.Error("Error: ${response.message()}")
}
}

// Check if there is an Internet connection
private fun hasInternetConnection(): Boolean {
val connectivityManager = getApplication().getSystemService(
Context.CONNECTIVITY_SERVICE
) as ConnectivityManager
val activeNetwork = connectivityManager.activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
}

// Prepare queries for the API
fun applyQueries(): HashMap {
val queries = HashMap()
queries[QUERY_NUMBER] = "50"
queries[QUERY_API_KEY] = API_KEY
queries[QUERY_TYPE] = "main course" // Adjust the recipe type here if necessary
queries[QUERY_DIET] = "vegan" // Adjust the type of diet if necessary
queries[QUERY_ADD_RECIPE_INFORMATION] = "true"
queries[QUERY_FILL_INGREDIENTS] = "true"
return queries
}
}
< /code>
Девизиаты Грэдли: < /p>
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
id("com.google.gms.google-services") // Agrega esta línea firebase config
id("androidx.navigation.safeargs.kotlin")
id("com.google.dagger.hilt.android")
id ("kotlin-kapt")
id ("kotlin-parcelize")
}

android {
namespace = "com.example.smartfreezer"
compileSdk = 35

defaultConfig {
applicationId = "com.example.smartfreezer"
minSdk = 24
targetSdk = 35
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
buildFeatures {
compose = true
viewBinding = true
dataBinding = true
}
}

dependencies {
implementation("com.google.code.gson:gson:2.8.8")
// Importa la BoM de Firebase para gestionar versiones automáticamente
implementation(platform("com.google.firebase:firebase-bom:33.12.0"))
// Servicios de Firebase (autenticación y Firestore)
implementation("com.google.firebase:firebase-auth")
implementation("com.google.firebase:firebase-firestore")
//Menu SmoothBottomBar
implementation("com.github.ibrahimsn98:SmoothBottomBar:1.7.9")
//Menu desplegable PowerSpinner
implementation ("com.github.skydoves:powerspinner:1.2.7")
implementation ("com.github.skydoves:powermenu:2.2.4")
implementation("com.google.android.material:material:1.12.0")
// Retrofit
implementation ("com.squareup.retrofit2:retrofit:2.9.0")
implementation ("com.squareup.retrofit2:converter-gson:2.9.0")
// ViewModel + LiveData + Hilt
implementation ("androidx.lifecycle:lifecycle-viewmodel-ktx")
implementation ("androidx.lifecycle:lifecycle-livedata-ktx")
implementation ("androidx.lifecycle:lifecycle-extensions:2.2.0")
implementation ("androidx.hilt:hilt-common:1.1.0")
implementation ("androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2")

// Glide para imágenes
implementation ("com.github.bumptech.glide:glide:4.12.0")
implementation ("com.github.bumptech.glide:compiler:4.12.0")

implementation("com.squareup.okhttp3:okhttp:4.11.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.11.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
// Hilt
implementation("com.google.dagger:hilt-android:2.56.1")
kapt ("com.google.dagger:hilt-android-compiler:2.56.1")
//Cargar imagen
implementation("io.coil-kt:coil:2.4.0")
//Parsear html
implementation("org.jsoup:jsoup:1.16.1")

//Shimmer
implementation ("com.facebook.shimmer:shimmer:0.5.0")
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation(libs.material)
implementation(libs.androidx.appcompat)
implementation(libs.androidx.constraintlayout)
implementation(libs.androidx.navigation.fragment.ktx)
implementation(libs.androidx.navigation.ui.ktx)
implementation(libs.androidx.activity)
implementation(libs.androidx.recyclerview)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}


Подробнее здесь: https://stackoverflow.com/questions/795 ... om-the-api
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

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