Room : DB๋ฅผ ํธํ๊ฒ ์ฐ๊ธฐ ์ํ ๊ฒ
Retrofit : HTTP ํต์ ์ ํธํ๊ฒ ํ๊ธฐ ์ํ ๊ฒ
์ธํฐ๋ท ๊ถํ ์ถ๊ฐ
์ ํ๋ฆฌ์ผ์ด์
์ด ํ๋ฌธ(HTTP) ๋คํธ์ํฌ ํธ๋ํฝ์ ์ฌ์ฉํ ์ ์๋๋ก ์ค์
<uses-permission android:name="android.permission.INTERNET"/>
android:usesCleartextTraffic="true"
implementation("com.google.code.gson:gson:2.10.1")
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
implementation("com.squareup.okhttp3:okhttp:4.10.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.10.0")
DustDTO ์์ฑ
์๋ฒ์์ ๋ณด๋ด์ฃผ๋ JSON ๊ฐ์ ๋ฐ์ดํฐ ํด๋์ค๋ฅผ ์ฝ๊ฒ ์์ฑํ๊ธฐ ์ํด ํ๋ฌ๊ทธ์ธ ์ฌ์ฉ
File>Settings>Plugins>"JSON To Kotlin Class install"ํ๊ธฐ
res>New>Kotlin data class File from JSON ๋๋ฅด๊ธฐ
JSON ํ์ผ์ ์
๋ ฅํ๊ณ (format์ ๋๋ฅด๊ณ ) Class Name์ ์
๋ ฅํ๋ฉด ์๋์ฒ๋ผ Data Class๋ค์ด ๋ง๋ค์ด์ง๋ค.
data class Dust(
val response: DustResponse
)
data class DustResponse(
@SerializedName("body")
val dustBody: DustBody,
@SerializedName("header")
val dustHeader: DustHeader
)
data class DustBody(
val totalCount: Int,
@SerializedName("items")
val dustItems: MutableList<DustItem>?,
val pageNo: Int,
val numOfRows: Int
)
์ด๋ ์ฃผ์๋ก ์ด๋ค ์์ฒญ ๋ณ์๋ฅผ ์ฃผ๊ณ ์ด๋ค ๊ฐ์ ๋ฐ๋์ง
ํ์ฑ์ Gson์ด ํด์ค
interface NetworkInterface {
@GET("getCtprvnRltmMesureDnsty") //์๋๋ณ ์ค์๊ฐ ์ธก์ ์ ๋ณด ์กฐํ ์ฃผ์
suspend fun getDust(@QueryMap param: HashMap<String, String>): Dust //HashMap์ ์์ฒญ๋ณ์๋ค์ด ๋ค์ด๊ฐ ex)์๋น์คํค, ํ์ด์ง ๋ฒํธ, ์๋๋ช
...
}
//Retrofit Client
object NetWorkClient {
private const val DUST_BASE_URL = "http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/"
private fun createOkHttpClient(): OkHttpClient {
val intercepter = HttpLoggingInterceptor()
//ํต์ ์ด ์ ์ ๋ ๋ ๋๋ฒ๊น
์ ์ํ ์ฉ๋๋ก ๋ฃ์ ๊ฒ
if (BuildConfig.DEBUG){
intercepter.level = HttpLoggingInterceptor.Level.BODY
} else{
intercepter.level = HttpLoggingInterceptor.Level.NONE
}
return OkHttpClient.Builder()
.connectTimeout(20,TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addNetworkInterceptor(intercepter)
.build()
}
private val dustRetrofit = Retrofit.Builder()
.baseUrl(DUST_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(createOkHttpClient())
.build()
val dustNetWork: NetworkInterface = dustRetrofit.create(NetworkInterface::class.java)
}
ํญ๋ชฉ๋ช
์ ๊ทธ๋๋ก ์ ์ด์ผ ํ๋ค.
private fun setUpDustParameter(sido: String): HashMap<String, String> {
val authKey =
"nrOGw0QURU.........."
return hashMapOf(
"serviceKey" to authKey,
"returnType" to "json",
"numOfRows" to "100",
"pageNo" to "1",
"sidoName" to sido,
"ver" to "1.0"
)
}
๋ฐ์ดํฐ ํต์ ์ ํด์ผ ํ๊ธฐ ๋๋ฌธ์ ๋ณ๋์ ์ค๋ ๋ ์์์ ์คํ
private fun communicateNetWork(param: HashMap<String, String>) = lifecycleScope.launch {
val responseData = NetWorkClient.dustNetWork.getDust(param)
items = responseData.response.dustBody.dustItems!!
val goo = ArrayList<String>()
items.forEach {
Log.d("add Item: ", it.stationName)
goo.add(it.stationName)
}
runOnUiThread {
binding.spinnerViewGoo.setItems(goo)
}
}