Skip to content

Instantly share code, notes, and snippets.

@Evin1-
Last active August 5, 2020 02:26
Show Gist options
  • Save Evin1-/f8a24052f9c615ed7be818fd5f399346 to your computer and use it in GitHub Desktop.
Save Evin1-/f8a24052f9c615ed7be818fd5f399346 to your computer and use it in GitHub Desktop.
Loop Cupcakes. Network call with Retrofit
<uses-permission android:name="android.permission.INTERNET" />
// build.gradle (:app)
android {
//..
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
//.. https://square.github.io/retrofit/
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* Creates an instance of the UserService using a simple Retrofit builder using Moshi
* as a JSON converter, this will append the endpoints set on the UserService interface
* (for example '/api', '/api?results=2') with the base URL set here, resulting on the
* full URL that will be called: 'https://randomuser.me/api' */
val service = Retrofit.Builder()
.baseUrl("https://randomuser.me/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(UserService::class.java)
/* Calls the endpoint set on getUsers (/api) from UserService using enqueue method
* that creates a new worker thread to make the HTTP call */
service.getUsers().enqueue(object : Callback<UserResponse> {
/* The HTTP call failed. This method is run on the main thread */
override fun onFailure(call: Call<UserResponse>, t: Throwable) {
Log.d("TAG_", "An error happened!")
t.printStackTrace()
}
/* The HTTP call was successful, we should still check status code and response body
* on a production app. This method is run on the main thread */
override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
/* This will print the response of the network call to the Logcat */
Log.d("TAG_", response.body())
}
})
}
}
/* Kotlin data/model classes that map the JSON response, we could also add Moshi
* annotations to help the compiler with the mappings on a production app */
data class UserResponse(val results: List<User>)
data class User(val email: String, val phone: String)
/* Retrofit service that maps the different endpoints on the API, you'd create one
* method per endpoint, and use the @Path, @Query and other annotations to customize
* these at runtime */
interface UserService {
@GET("/api")
fun getUsers(): Call<UserResponse>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment