OkHttp request Kotlin / Jetpack

20 views Asked by At

I am trying to request JSON from an endpoint, and to dump this information in raw form on the screen - the next step will be to do this with the click of a button. I am completely new to Kotlin, so please be gentle (it is a new team member challenge as part of my employment) I was hoping to try and figure it out by myself and I feel like I might be almost there but not able to connect all the dots.

Here is my MainActivity.kt file:

package com.example.myfilename

import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.material3.Text
import androidx.compose.ui.tooling.preview.Preview
import okhttp3.OkHttpClient
import okhttp3.*
import java.io.IOException

class MainActivity : ComponentActivity() {
    private val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // variable to hold the JSON response
            var jsonResponse by remember { mutableStateOf("Waiting for response...") }

            // function to fetch JSON data and update the variable
            fetchData { response ->
                jsonResponse = response ?: "Failed to fetch data"
            }

            // Display the JSON response
            DisplayJsonResponse(jsonResponse)
        }
    }

    private fun fetchData(onResult: (String?) -> Unit) {
        val client = OkHttpClient()
        val url = "EXAMPLEURL.json"
        val request = Request.Builder().url(url).build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // Handle failure
                e.printStackTrace()
                onResult(null)

            }

            override fun onResponse(call: Call, response: Response) {
                // Handle success
                val responseBody = response.body?.string()
                onResult(responseBody)
            }
        })
    }


}

// Composable function to display the JSON response
@Composable
private fun DisplayJsonResponse(jsonResponse: String) {
    Text(
        text = jsonResponse,
        modifier = Modifier.fillMaxSize()
    )
}

@Preview(showBackground = true)
@Composable
private fun DisplayJsonResponsePreview() {
    DisplayJsonResponse("Sample JSON Response")
}





//    private val client = OkHttpClient()
//
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        setContent {
//            BbcsoundsminichallengeTheme {
//                var jsonResponse by remember { mutableStateOf("waiting...") }
//
//                // Composable function to display JSON response
//                DisplayJsonResponse(jsonResponse)
//
//                val url = "https://sounds-mobile-config.files.bbci.co.uk/android/2.3.0/config.json"
//                val request = Request.Builder().url(url).build()
//
//                client.newCall(request).enqueue(object : Callback {
//                    override fun onFailure(call: Call, e: IOException) {
//                        e.printStackTrace()
//                        jsonResponse = "Failed to fetch data"
//                    }
//
//                    override fun onResponse(call: Call, response: Response) {
//                        if (response.isSuccessful) {
//                            val responseBody = response.body?.string()
//                            responseBody?.let {
//                                // Update the UI on the main thread
//                                LaunchedEffect(Unit) {
//                                    jsonResponse = it
//                                }
//                            }
//                        } else {
//                            jsonResponse = "Failed to fetch data"
//                        }
//                    }
//                })
//            }
//        }
//    }
//}
//
//@Composable
//fun DisplayJsonResponse(jsonResponse: String) {
//    Text(
//        text = jsonResponse,
//        modifier = Modifier.fillMaxSize()
//    )
//}
//
//@Preview(showBackground = true)
//@Composable
//fun DisplayJsonResponsePreview() {
//    BbcsoundsminichallengeTheme {
//        DisplayJsonResponse("sample response")
//    }
//}

(have replaced the file name and url for the request to remove identifiables)

0

There are 0 answers