0.前言

從Android 利用 Retrofit library get SpringBoot Data , SpringBoot Create , [Java]SpringBoot-MySQL-API

1.準備

Gradle

AnkoLogger , Gson , Retrofit and he’s converter

//lib AnkoLogger
implementation "org.jetbrains.anko:anko:0.10.8"
//lib Gson
implementation 'com.google.code.gson:gson:2.8.5'
//lib Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'

Have RecyclerView layout [Android] Kotlin-RecyclerView

2.Code

Create retrofit object

use 10.0.2.2 instead of localhost

val retrofit: Retrofit = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(
            GsonBuilder()
                .setLenient()
                .serializeNulls()
                .create()

        ))
        .baseUrl("http://10.0.2.2:8080/demo2User/")
        .build()

Create interface  All action here “UserService”

@Get()

@POST(“”) ,

  • if return String , need use ResponseBody to get it
  • send an object need “@Body”
interface UserService {
    @GET("allUsers")
    fun  getUserList() : Call<List<User>>

    @POST("add")
    @FormUrlEncoded
    fun insertUser(
        @Field("name") name: String,
        @Field("email") email: String
    ) :Call<ResponseBody>

    @POST("addUser")
    fun insertUserByObject(
         @Body user : User
    ) :Call<ResponseBody>

    @POST("delete")
    fun deletetUserByObject(
        @Body user : User
    ) :Call<ResponseBody>

}

LoadData() , use @GET

use Anko , doAsync  block ,

  • declare service
  • use service function . execute .body
private fun loadData() {
        doAsync {
        val userService = retrofit.create(UserService::class.java)
        data = userService.getUserList().execute().body()
        data?.forEach {
           // info("${it.id} , ${it.name}  , ${it.email}")
        }
            uiThread {
                userRecycler.setHasFixedSize(true)
                userRecycler.layoutManager = LinearLayoutManager(this@SpringBootTestActivity)
                userRecycler.adapter = UserAdapter()
            }
        }

    }

InsertData(view:View) when button click

use enqueue can implement Callback function

fun insertData (view : View){
        doAsync {
            val userService = retrofit.create(UserService::class.java)
            val user = User(email = "lee@com.tw",name = "lee",id = 100)
            //val msg = userService.insertUser(user.name,user.email).execute().body()
            val msg = userService.insertUserByObject(user).enqueue(object :Callback<ResponseBody>{
                override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        info("onFailure  ${t.message}")
                }

                override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                    if (response.isSuccessful){
                        info("onResponse  ${response.body()?.string()}")
                        loadData()

                    }
                }

            })

        }

    }

 

 

 

 

 

 

 

 

 

 

 

最後修改日期: 2019-05-06 11:51:39

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料