简体   繁体   中英

How to add Text Composable in onResponse ? Jetapck Compose

My English is weak so please manage

I'm trying to get data from json after decoding json How can i add the decoded data to a Text Composable

Here is my Code

@Composable
fun Api(){
    val url = "https://jsonplaceholder.typicode.com/posts"
    val request = Request.Builder().url(url).build()
    val client = OkHttpClient()
    client.newCall(request).enqueue(object : Callback{
        override fun onResponse(call: Call, response: Response) {
            val body = response.body()?.string()
            val gson = Gson()
            val bundle = gson.fromJson(body, Array<Json>::class.java)
            for(element in bundle){
                val title = element.title
                TODO("How to add title value to Text Composable")
            }
        }
        override fun onFailure(call: Call, e: IOException) {
            print("Error")
        }
    })
}

Here is my Data class


data class Json(
    @field:SerializedName("title")
    val title: String? = null,
)

You should move your logic in a ViewModel, loading the data and expose the value to the Text as a state.

If you want to use your example you can define your Text :

var text by remember { mutableStateOf("") }
Text (text = text)

Then just update the text value:

client.newCall(request).enqueue(object : Callback {
             //...

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    //....
                    text = //your logic
                }
            }
        })

My English is weak so please manage

I'm trying to get data from json after decoding json How can i add the decoded data to a Text Composable

Here is my Code

@Composable
fun Api(){
    val url = "https://jsonplaceholder.typicode.com/posts"
    val request = Request.Builder().url(url).build()
    val client = OkHttpClient()
    client.newCall(request).enqueue(object : Callback{
        override fun onResponse(call: Call, response: Response) {
            val body = response.body()?.string()
            val gson = Gson()
            val bundle = gson.fromJson(body, Array<Json>::class.java)
            for(element in bundle){
                val title = element.title
                TODO("How to add title value to Text Composable")
            }
        }
        override fun onFailure(call: Call, e: IOException) {
            print("Error")
        }
    })
}

Here is my Data class


data class Json(
    @field:SerializedName("title")
    val title: String? = null,
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM