项目作者: Jeluchu

项目描述 :
Example of using API with Retrofit 2 (Weather App)
高级语言: Kotlin
项目地址: git://github.com/Jeluchu/retrofitAPI.git
创建时间: 2019-02-04T12:42:15Z
项目社区:https://github.com/Jeluchu/retrofitAPI

开源协议:

下载


RETROFIT API EXAMPLE

API
Download

INTRODUCTION

Test to get data from Open Weather Map and show temperature (now, min and max), humidity, pressure and country. For it, I’m using Retrofit 2 a library for Android. This app is for Kotlin 100%

Implementation library on build.gradle (Module:app)

  1. implementation 'com.squareup.retrofit2:retrofit:2.5.0'
  2. implementation 'com.squareup.retrofit2:converter-gson:2.5.0' // for convert JSON

It’s very important to put in the Manifest the next permission

  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>

WEATHER SERVICE

In the WeatherService (interface), you GET de data, doing the query to the data that you need

  1. @GET("data/2.5/weather?")
  2. fun getCurrentWeatherData(@Query("lat") lat: String, @Query("lon") lon: String, @Query("APPID") app_id: String): Call<WeatherResponse>

¡Not all API’s have the same pattern, so keep that in mind!

WEATHER RESPONSE

Serialized Name the value that I collect from the API and convert it to a float (in these case)

  1. @SerializedName("temp")
  2. var temp: Float = 0.0f
  3. [...]
  4. @SerializedName("country")
  5. var country: String? = null
  6. [...]

MAIN ACTIVITY

I create a function from which we will implement the base link where the API is located, and we will access it. In addition we will implement another function in which we will show the data by screen

  1. val retrofit = Retrofit.Builder()
  2. .baseUrl(BaseUrl)
  3. .addConve
  4. val service = retrofit.create(WeatherService::class.java)
  5. val call = service.getCurrentWeatherData(lat, lon, AppId)
  1. val stringBuilder = Html.fromHtml(
  2. "<b>País:</b> " + weatherResponse.sys!!.country + "<br>" +
  3. "<b>Temperatura:</b> " +(weatherResponse.main!!.temp - 273 ) + " ºC"
  4. [...]

And finally, a Companion Object is created in which we will introduce the data of the variables, such as the link, base, longitude / latitude, etc.