/
GreyStekl0
/
WeatherAppCompose
Обзор
Документация
Войти
/
GreyStekl0
/
WeatherAppCompose
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
app/src/main/java/com/example/weatherappcompose/MainActivity.kt
198 строк
6 KB
Stekl0
Refactor to Retrofit
17 фев 2025, 17:14
17 фев 2025, 17:14
25b17a8
Код
Авторство
О чём код?
package com.example.weatherappcompose import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import com.example.weatherappcompose.data.WeatherModel import com.example.weatherappcompose.screens.DialogSearch import com.example.weatherappcompose.screens.MainCard import com.example.weatherappcompose.screens.TabLayout import com.example.weatherappcompose.ui.theme.WeatherAppComposeTheme import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.http.GET import retrofit2.http.Query const val API_KEY = "e690691918564489856160550240608" class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { val dayList = remember { mutableStateOf(listOf<WeatherModel>()) } val dialogState = remember { mutableStateOf(false) } val currentDay = remember { mutableStateOf(WeatherModel()) } if (dialogState.value) { DialogSearch(dialogState, onSubmit = { getData(it, dayList, currentDay) }) } getData("Moscow", dayList, currentDay) WeatherAppComposeTheme { Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -> Column(modifier = Modifier.padding(innerPadding)) { MainCard(currentDay, onClickSync = { getData("London", dayList, currentDay) }, onClickSearch = { dialogState.value = true }) TabLayout(dayList, currentDay) } } } } } } // private fun getData( // city: String, // dayList: MutableState<List<WeatherModel>>, // currentDay: MutableState<WeatherModel>, // ) { // val url = // "https://api.weatherapi.com/v1/forecast.json" + // "?key=$API_KEY" + // "&q=$city" + // "&days=3" + // "&aqi=no&alerts=no" // Fuel.get(url).responseString { _, _, result -> // result.fold( // success = { data -> // dayList.value = getWeatherByDays(data) // currentDay.value = dayList.value[0] // }, // failure = { error -> // Log.d("MyLog", "fuelError: ${error.message}") // }, // ) // } // } // Определяем интерфейс для API interface WeatherApiService { @GET("forecast.json") fun getForecast( @Query("key") apiKey: String, @Query("q") city: String, @Query("days") days: Int, @Query("aqi") aqi: String, @Query("alerts") alerts: String, ): Call<String> } // Функция для получения данных private fun getData( city: String, dayList: MutableState<List<WeatherModel>>, currentDay: MutableState<WeatherModel>, ) { val retrofit = Retrofit .Builder() .baseUrl("https://api.weatherapi.com/v1/") .addConverterFactory(ScalarsConverterFactory.create()) .build() val service = retrofit.create(WeatherApiService::class.java) val call = service.getForecast(API_KEY, city, 3, "no", "no") call.enqueue( object : Callback<String> { override fun onResponse( call: Call<String>, response: Response<String>, ) { if (response.isSuccessful && response.body() != null) { val data = response.body()!! dayList.value = getWeatherByDays(data) currentDay.value = dayList.value[0] } else { Log.d("MyLog", "Response error: ${response.errorBody()?.string()}") } } override fun onFailure( call: Call<String>, t: Throwable, ) { Log.d("MyLog", "retrofitError: ${t.message}") } }, ) } private fun getWeatherByDays(response: String): List<WeatherModel> { if (response.isEmpty()) return listOf() val list = ArrayList<WeatherModel>() val mainObject = JSONObject(response) val city = mainObject.getJSONObject("location").getString("name") val days = mainObject.getJSONObject("forecast").getJSONArray("forecastday") for (i in 0 until days.length()) { val item = days[i] as JSONObject list.add( WeatherModel( city, item.getString("date"), "", item .getJSONObject("day") .getJSONObject("condition") .getString("text"), item .getJSONObject("day") .getJSONObject("condition") .getString("icon"), item .getJSONObject("day") .getString("maxtemp_c") .toFloat() .toInt() .toString() + "℃", item .getJSONObject("day") .getString("mintemp_c") .toFloat() .toInt() .toString() + "℃", item.getJSONArray("hour").toString(), ), ) } list[0] = list[0].copy( time = mainObject.getJSONObject("current").getString("last_updated"), currentTemp = mainObject .getJSONObject("current") .getString("temp_c") .toFloat() .toInt() .toString() + "℃", ) return list }