Reputation: 91
I'm trying to fetch an api data by Volley connection and assign into Text Composable, but it didn't work and showing error:
@Composable invocations can only happen from the context of a @Composable function
I know that There is a similar question but it didn't solve me my problem
how can i solve this error? because I'm New in Jetpack compose
CODE:
@Composable
fun getJSON() {
val context = LocalContext.current
val queue = Volley.newRequestQueue(context)
val url = "https://adeega.xisaabso.online/android.php"
val stringRequest = StringRequest(Request.Method.POST, url,
{ response ->
val jsonObject = JSONObject(response)
val TotalMoney = jsonObject.get("Total")
Text(text = "$TotalMoney")
},
{
Toast.makeText(context, "Welcome to Error", Toast.LENGTH_SHORT).show()
})
queue.add(stringRequest)
}
SetContent
setContent {
First_JetpackCompose_appTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
getJSON()
} // END Surface
}
}
Upvotes: 0
Views: 563
Reputation: 364730
You can't use Text(text = "$TotalMoney")
in the response
block.
Use a ViewModel
or just use something like:
var totalMoney by remember { mutableStateOf("") }
Text(text = totalMoney)
val stringRequest = StringRequest(Request.Method.POST, url,
{ response ->
/* Your code */
totalMoney = ....
},
{
Toast.makeText(context, "Welcome to Error", Toast.LENGTH_SHORT).show()
})
queue.add(stringRequest)
Upvotes: 0