5

I'm new to Kotlin, Android and OOP in general (Natural-ADABAS background, never did Java, C++, etc) so I'm pretty desperate.

I have an API whose data looks like this, an array of book details:

API data sample

enter image description here

I'm confused about data models. I know it's supposed to look like how the data in the API and return an array but how exactly do I code it in Kotlin? And then how do I parse it? I've read some tutorials but they all differ. Some use an object, and some use a class.

I'm also probably breaking some standard by putting everything in the main activity but I haven't gotten to that part yet.

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query

class MainActivity : AppCompatActivity()

 {

private val api: RestAPI = RestAPI()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)


    val apiGetBooks = api.getBooksList("token123123123")
    val response = apiGetBooks.execute()


    if (response.isSuccessful) {
        val books = response.body()?.title
        println(books)

    } else {
        println("error on API") // What do I do?
    }

}

object  Model {
    val ResultArray : MutableList<BookProperties>? = null
}

data class BookProperties (val id: Int,val title: String, val coverURI: String, val pageURI: String, val pageCount: Int, val languageId: Int,val  description: String, val isFree: Boolean) {
}

private val buriApi: MainActivity.BooksAPI? = null

class RestAPI {
    private val buriApi: BooksAPI

    init {
        val retrofit = Retrofit.Builder()
                .baseUrl("https://api.someurl.com")
                .addConverterFactory(MoshiConverterFactory.create())
                .build()

        buriApi = retrofit.create(BooksAPI::class.java)
    }

    fun getBooksList(token: String): Call<BookProperties>{
        return buriApi.getBooks(token)
    }
}

fun getBooksList(token: String): Call<MainActivity.BookProperties> {
    return buriApi!!.getBooks(token)
}

interface  BooksAPI {
    @GET("/v1/books")
    fun getBooks (@Query("token")token: String) : Call<BookProperties>
}
}

2 Answers 2

4

After much googling, I finally solved my problem thanks to How to Quickly Fetch Parse JSON with OkHttp and Gson on YouTube.

    fun fetchBooks () {
    println("fetching books")

     val url = "https://api.someurl.com/v1/books?"
    val request = Request.Builder().url(url).build()

    println(request)
    val client = OkHttpClient()

    client.newCall(request).enqueue(object: Callback {
        override fun onResponse(call: Call?, response: Response?) {
            val body = response?.body()?.string()
            println(body)
        }

        override fun onFailure(call: Call?, e: IOException?) {
            println("Failed to execute request")
            e?.printStackTrace()
        }
    })
}

Still need to format the data and figure out how to turn on wifi in my Android emulator but at least I can consume the JSON.

Sign up to request clarification or add additional context in comments.

Comments

0

Let's start with a sample and I guess you can map it accordingly to your requirement.

I don't have your JSON as text so I am giving an example of mine.

sample JSON response

    {
     "status": true,
     "message": "User created Successfully.",
     "response": {
     "user": {
     "id": 12,
     "email": "[email protected]"
    },
     "token": "eyJlbWFpbCI6ImVzaGFudHNhaHUxMTBAZ21hc2kyMmwuY29tIiwidXNlcklkIjoxNSwiaWF0IjoxNTIxNTYyNjkxfQ"
    }
   }

so create a new class and name it something like this

CreateResponse.kt and just map those objects and arrays from json to data classes and list here.

data class CreateUserResponse(override val status: Boolean? = null,
                                  override val message: String? = null,
                                  val response: Response? = null) 

data class Response(val user: User?, val token: String)

data class User(val id: Int, val email: String)

easy right, now with Kotlin you can declare your data classes without creating separate files each time for each object just create one file and declare all of them at once.

I'm attaching some of the resources here which may help you understand the things better.

https://antonioleiva.com/retrofit-android-kotlin/

https://segunfamisa.com/posts/using-retrofit-on-android-with-kotlin

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.