Lesson 11 - Connect To The Internet
Lesson 11 - Connect To The Internet
Connect to the
internet
In AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-
moshi:2.9.0"
implementation "com.squareup.moshi:moshi:$moshi_version"
implementation "com.squareup.moshi:moshi-kotlin:
$moshi_version"
kapt "com.squareup.moshi:moshi-kotlin-codegen:
$moshi_version"
This work is licensed under the
Android Development with Kotlin Apache 2 license. 15
Connect to a web
service
● GET
● POST
● PUT
● DELETE
@GET("posts/{userId}")
suspend fun listByUser(@Path("userId") userId:String):
List<Post>
@POST("posts/new")
suspend fun create(@Body post : Post):ThisPost
work is licensed under the
} Android Development with Kotlin Apache 2 license. 19
Create a Retrofit object for
network access
val retrofit = Retrofit.Builder()
.baseUrl("https://example.com")
.addConverterFactory(...)
.build()
Retrofit
Service HTTP Request
App UI
Server
ViewMod HTTP
Web API
el Response
(JSON
Converter )
Moshi
List of
JSON
Post Moshi
response
objects
@JsonClass(generateAdapter = true)
data class Post (
val title: String,
val description: String,
val url: String,
val updated: String,
val thumbnail: String,
val closedCaptions: String?)
{
"title":"Android Jetpack: EmojiCompat",
"description":"Android Jetpack: EmojiCompat",
"url":"https://www.youtube.com/watch?v=sYGKUtM2ga8",
"updated":"2018-06-07T17:09:43+00:00",
"thumbnail":"https://i4.ytimg.com/vi/sYGKUtM2ga8/hqdefault.jpg
"
}
viewModelScope.launch {
Log.d("posts", API.retrofitService.searchPosts("query"))
}
implementation "com.github.bumptech.glide:glide:
$glide_version"
Glide.with(fragment)
.load(url)
.into(imageView);
Glide.with(imgView)
.load(imgUri)
.apply(RequestOptions()
.placeholder(R.drawable.loading_animation)
.error(R.drawable.ic_broken_image))
.into(imgView)
}
} This work is licensed under the
Android Development with Kotlin Apache 2 license. 33
Summary