Код: Выделить всё
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
CoroutineScope(Dispatchers.IO).launch {
val response = async {
try {
val url = URL(getString(R.string.api_endpoint))
val urlConnection = url.openConnection()
val inputStream = urlConnection.getInputStream()
val reader = BufferedReader(InputStreamReader(inputStream))
val stringBuilder = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
stringBuilder.append(line)
}
reader.close()
inputStream.close()
val jsonString = stringBuilder.toString()
val gson = Gson()
val data = gson.fromJson(jsonString, Pondus::class.java)
data
} catch (e: Exception) {
Log.d("DEBUG exception", e.toString())
}
}.await()
withContext(Dispatchers.Main) {
setContent {
PondusTheme {
InputValues(response)
}
}
}
}
}
@Composable
fun InputValues(result: Any) {
var statusText by remember { mutableStateOf("") }
Column {
Row {
TextField(
value = statusText,
onValueChange = { statusText = it },
)
}
Row {
MakeButton()
}
}
}
@Composable
private fun MakeButton() {
Button(onClick = { sendValue(23.4F) }) {
Text(text = "Some text goes here")
}
}
private fun sendValue(value: Float): Boolean {
CoroutineScope(Dispatchers.IO).launch {
val response = async {
// Perform network operation here
val client = HttpClient()
val response: HttpResponse =
client.post(getString(R.string.api_endpoint_2)) {
setBody("Body content")
}
}.await()
withContext(Dispatchers.Main) {
// Update status_text here
Подробнее здесь: [url]https://stackoverflow.com/questions/79012343/update-the-text-of-a-kotlin-text-field[/url]