- Разработка приложений для прогнозирования погоды на Kotlin: использование API OpenWeather и DarkSky
- Похожие записи:
- Saved searches
- Use saved searches to filter your results more quickly
- gurleensethi/kotlin-weather
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Saved searches
- Use saved searches to filter your results more quickly
- License
- dsckiet/weather-app-kotlin
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- Readme.md
- Free open source weather app which shows you the current weather details and forecast for up to seven days.
- Functionalities
- Usage and screenshots
- View temps in both Fahrehheit and Celsius:
- Weather forecast for the next seven days:
- Specify custom location or access current location:
- Instructions to run
- Contributors
- About
- Saved searches
- Use saved searches to filter your results more quickly
- License
- ekamp/KotlinWeather
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Разработка приложений для прогнозирования погоды на Kotlin: использование API OpenWeather и DarkSky
Разработка приложений для прогнозирования погоды уже давно не новость. Однако, программирование таких приложений всегда остаётся актуальной задачей. В данной статье мы рассмотрим как создавать приложения для прогнозирования погоды на языке программирования Kotlin, используя API OpenWeather и DarkSky.
OpenWeather и DarkSky — это два из самых популярных и надежных сервисов прогнозирования погоды, которые предоставляют стандартное и точное прогнозирование погоды по всему миру. Чтобы использовать их API для разработки приложений на Kotlin, мы будем использовать их совместимость с Kotlin.
Чтобы начать разработку, вам понадобится:
1. Получить API Key для OpenWeather и DarkSky. Каждый API имеет свою документацию, которую необходимо изучить, чтобы получить ключ.
2. Использовать библиотеки для подключения к API. Например, для OpenWeather можно использовать Retrofit, а для DarkSky — OkHttp.
3. Архитектура приложения. Мы будем использовать архитектурный шаблон Model-View-ViewModel (MVVM), который позволяет лучше организовать код и упростить поддержку.
4. Интерфейс пользователя. Это картинка, с которой пользователь общается с вашим приложением для прогнозирования погоды. Мы будем использовать естественный дизайн, который предоставляет Google Material Design для создания аккуратного и функционального пользовательского интерфейса.
5. Инструменты для разработки. Для разработки на Kotlin можно использовать Android Studio — наиболее популярный инструмент, специально созданный для разработки Android-приложений.
Приступим к созданию проекта.
Создайте новый проект в Android Studio, выбрав шаблон пустой активности. Ознакомьтесь с базовым макетом пользовательского интерфейса и добавьте необходимые элементы макета для отображения результатов прогноза погоды.
Добавьте необходимые зависимости для работы с Retrofit (для OpenWeather), OkHttp (для DarkSky) и дополнительные библиотеки для Android. Эти библиотеки позволяют легко работать с RecyclerView, загружать изображения из интернета и многое другое.
// Retrofit для OpenWeather implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // OkHttp для DarkSky implementation "com.squareup.okhttp3:okhttp:4.9.1" // Библиотеки для Android implementation 'com.google.android.material:material:1.1.0' implementation 'com.squareup.picasso:picasso:2.5.2' implementation 'androidx.recyclerview:recyclerview:1.2.0-beta01'
Теперь, необходимо добавить доступ к интернету в манифесте приложения.
Шаг 2: Создание API для OpenWeather и DarkSky
Создайте классы модели и интерфейсы для работы с OpenWeather и DarkSky.
data class OpenWeather( val weather: List, val main: Main, val name: String, val dt: Int ) data class Weather( val description: String ) data class Main( val temp: Double, val humidity: Int ) interface OpenWeatherApi < @GET("weather") fun getWeather( @Query("q") city: String, @Query("appid") apiKey: String, @Query("units") units: String ): Call> data class DarkSky( val currently: Currently ) data class Currently( val temperature: Double, val summary: String ) interface DarkSkyApi < @GET(",") fun getWeather( @Path("lat") lat: String, @Path("lng") lng: String, @Query("units") units: String, @Query("exclude") exclude: String, @Query("lang") lang: String, @Query("apikey") apiKey: String ): Call >
Здесь мы определили классы модели для OpenWeather и DarkSky, а также интерфейсы API для получения погоды. Используйте эти интерфейсы в своем приложении, чтобы получить прогноз погоды.
Создайте ViewModel, который будет служить посредником между моделью и представлением. Он дает возможность получить данные из модели и передает информацию в представление.
class WeatherViewModel : ViewModel()
Шаг 4: Создание Repository
Создайте Repository, который использует API для получения данных.
class WeatherRepository < private val openWeatherApi: OpenWeatherApi private val darkSkyApi: DarkSkyApi init < val openWeatherClient = HttpClient( OkHttp, "https://api.openweathermap.org/data/2.5/" ) val darkSkyClient = HttpClient( OkHttp, "https://api.darksky.net/forecast/" ) openWeatherApi = openWeatherClient.create(OpenWeatherApi::class) darkSkyApi = darkSkyClient.create(DarkSkyApi::class) >fun getOpenWeather(city: String, apiKey: String) = liveData < emit(Resource.loading(null)) try < val response = openWeatherApi.getWeather(city, apiKey, "metric").execute() if (response.isSuccessful) < emit(Resource.success(response.body())) >else < emit(Resource.error(response.message(), null)) >> catch (e: IOException) < emit(Resource.error(e.message ?: "Unexpected error occurred", null)) >> fun getDarkSky(lat: String, lng: String, apiKey: String) = liveData < emit(Resource.loading(null)) try < val response = darkSkyApi.getWeather(lat, lng, "auto", "minutely,hourly,daily,alerts", "ru", apiKey).execute() if (response.isSuccessful) < emit(Resource.success(response.body())) >else < emit(Resource.error(response.message(), null)) >> catch (e: IOException) < emit(Resource.error(e.message ?: "Unexpected error occurred", null)) >> >
Шаг 5: Создание представления
Создайте представление, которое будет отображать результаты прогноза погоды. Это может быть любой из макетов Android Studio.
class MainActivity : AppCompatActivity() < private lateinit var viewModel: WeatherViewModel private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val repository = WeatherRepository() viewModel = ViewModelProvider(this).get(WeatherViewModel::class.java).apply < openWeatherService = OpenWeatherService(repository) darkSkyService = DarkSkyService(repository) >binding.btnSearch.setOnClickListener < val city = binding.etCity.text.toString() viewModel.getOpenWeather(city, "your_api_key").observe(this) < openWeatherResource ->when (openWeatherResource.status) < Resource.Status.LOADING -> < // Показываем индикатор загрузки >Resource.Status.SUCCESS -> < val openWeather = openWeatherResource.data val lat = openWeather?.let < it.coord.lat.toString() >?: "" val lon = openWeather?.let < it.coord.lon.toString() >?: "" viewModel.getDarkSky(lat, lon, "your_api_key").observe(this) < darkSkyResource ->when (darkSkyResource.status) < Resource.Status.LOADING -> < // Показываем индикатор загрузки >Resource.Status.SUCCESS -> < val darkSky = darkSkyResource.data updateUI(openWeather, darkSky) >Resource.Status.ERROR -> < // Показываем сообщение об ошибке >> > > Resource.Status.ERROR -> < // Показываем сообщение об ошибке >> > > > private fun updateUI(openWeather: OpenWeather?, darkSky: DarkSky?) < // Отображаем прогноз погоды >>
На этом, техническая часть нашего приложения для прогнозирования погоды готова. Напомним, что вам нужно получить ключи API от сервисов OpenWeather и DarkSky. Когда вы запускаете приложение в Emulator или на своем устройстве, вы можете ввести название города в текстовое поле приложения, чтобы получить прогноз погоды.
В заключении, мы надеемся, что данная статья помогла вам разобраться в разработке приложений для прогнозирования погоды на Kotlin с использованием API OpenWeather и DarkSky. Искренне желаем вам успеха и новых достижений в программировании!
Похожие записи:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Simple android weather app developed in kotlin, demonstrating the use of RxJava, Retrofit and implementing MVP.
gurleensethi/kotlin-weather
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Simple android weather app developed in kotlin, demonstrating the use of RxJava, Retrofit and implementing MVP.
Weather app created using the Weather Api from Mashape marketplace. This is not supposed to be a production scale application, it is meant to demonstrate the implementation of MVP architecture in Kotlin using following libraries:
Still if you have any issues or suggestions, please feel free to open an issue
- Check if there is cached data present in the internal file, if yes then load the cached data.
- Retrieve the latitude and longitude of the user.
- Request data from Weather Api
- If data received, cache it in internal file and show the updated data to user.
- If error then notify user about it.
To build the project on your own follow these steps:
- Clone the project
- Get an API key from Weather Api
- Create a Kotlin file named Secrets.kt
- In that file create an object and add a variable API_KEY that contains the key that you got from the Weather Api.
object Secrets < val API_KEY = "your_api_key" >
About
Simple android weather app developed in kotlin, demonstrating the use of RxJava, Retrofit and implementing MVP.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Get Instant Weather updates using the Weather App
License
dsckiet/weather-app-kotlin
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
Readme.md
Get instant weather updates using the Weather App.
Free open source weather app which shows you the current weather details and forecast for up to seven days.
Functionalities
- Hourly Weather Forecast
- 7 days Weather Forecast
- Time of Sunrise and Sunset
- Humidity and Wind Predictions
- Celsius to Farenheit conversion
- Access user location or provide custom location
Usage and screenshots
View temps in both Fahrehheit and Celsius:
Weather forecast for the next seven days:
Specify custom location or access current location:
Instructions to run
- Pre-requisites:
- Android Studio v4.0
- A working Android physical device or emulator with USB debugging enabled
- Clone this repository to your local storage using Git bash:
https://github.com/dsckiet/weather-app-kotlin
- Open this project from Android Studio
- Connect to an Android physical device or emulator
- To install the app into your device, run the following using command line tools
adb shell monkey -p com.example.weatherapp -c android.intent.category.LAUNCHER 1
Contributors
⭐ To contribute, please go through our contributing guide.
About
Get Instant Weather updates using the Weather App
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Short and Sweet Kotlin Weather Application
License
ekamp/KotlinWeather
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Short and Sweet Kotlin Weather Application
Small application that will present a user with Weather at their given location.
Setup API Key for Open Weather Map
1. Get API Key from Open Weather Map from https://home.openweathermap.org/api_keys 2. open app/build.gradle 3. replace with your api key you just registered 4. Sync your project with the updated Gradle file
- Jetbrains Kotlin : https://kotlinlang.org/
- Toothpick Dependency Injection : https://github.com/stephanenicolas/toothpick
- RxJava 2 / RxAndroid : https://github.com/ReactiveX/RxJava
- Retrofit 2 : http://square.github.io/retrofit/
- Picasso : http://square.github.io/picasso/
- EasyMock : http://easymock.org/
About
Short and Sweet Kotlin Weather Application