[英]Kotlin | API request with okhttp
Solution:解决方案:
class MainActivity : AppCompatActivity() {
lateinit var playerStats: PlayerStats
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Picasso.get().load("https://...../....../example.png").into(Viewer)
var PlayerName: String = ""
fun fetchJson() {
val url = "https://my.api.site/example/"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
var mainHandler = Handler(this@MainActivity.getMainLooper())
override fun onResponse(call: Call, response: Response) {
mainHandler.post {
val body = response.body()?.string()
if (body == null) return@post
println(body)
val gson = GsonBuilder().create()
playerStats = gson.fromJson(body, PlayerStats::class.java)
println(playerStats)
// TODO Now you can access to your view and set every thing to textView
textView.text = playerStats.username
}
}
override fun onFailure(call: Call, e: IOException) {
println("API execute failed")
}
})
}
buttonGO.setOnClickListener {
PlayerName = editText.text.toString()
fetchJson()
if (PlayerName == null || PlayerName.trim() == "") {
println("please input data, input cannot be blank")
} else {
Picasso.get().load("https://...../...../" + PlayerName + ".png")
.into(Viewer)
textView.setText(PlayerName).toString()
}
}
}
} ```
I have this code for my api request and it works when I use debugger .我的 api 请求有这个代码,当我使用debugger时它可以工作。
I can see the results in the PlayerStats class but now I have a problem.我可以在 PlayerStats 类中看到结果,但现在我遇到了问题。
But on the MainActivity.class
this function
don't work:但是在MainActivity.class
这个function
不起作用:
val url = "https://api.example.com/..../"
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()
println(body)
val gson = GsonBuilder().create()
val PlayerStats = gson.fromJson(body, PlayerStats::class.java)
println(PlayerStats)
}
override fun onFailure(call: Call, e: IOException) {
println("API execute failed")
}
})
Stats.class :统计类:
class PlayerStats(val username: String , val level: Double )
I need a way to get access to the val username
/ val level
from MainActivity
我需要一种方法来从MainActivity
访问val username
/ val level
class MainActivity(val mystats: PlayerStats) : AppCompatActivity(){
Not works, because of the zero arguments.不工作,因为零参数。
If I try to fix:如果我尝试修复:
class MyActivity: AppCompatActivity() {
var myStats: Stats? = null
//..
}
The IDE say it needs a safe call
or a non-null
asserted call but if I try this with the non-null
asserted call the application crash and i get this error: IDE 说它需要safe call
non-null
断言调用,但是如果我尝试使用non-null
断言调用进行此操作,应用程序将崩溃,并且出现此错误:
2020-03-05 18:58:02.803 23276-23276/my.example.package E/AndroidRuntime: FATAL EXCEPTION: main Process: my.example.package, PID: 23276 kotlin.KotlinNullPointerException at my.example.package.MainActivity$onCreate$1.invoke(MainActivity.kt:31) at my.example.package.MainActivity$onCreate$3.onClick(MainActivity.kt:68) at android.view.View.performClick(View.java:7125) at android.view.View.performClickInternal(View.java:7102) at android.view.View.access$3500(View.java:801) at android.view.View$PerformClick.run(View.java:27336) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7356) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 2020-03-05 18:58:02.803 23276-23276/my.example.package E/AndroidRuntime:致命异常:主进程:my.example.package,PID:23276 kotlin.KotlinNullPointerException at my.example.package.MainActivity onCreate$1.invoke(MainActivity.kt:31) at my.example.package.MainActivity$onCreate$3.onClick(MainActivity.kt:68) at android.view.View.performClick(View.java:7125) at android.view .View.performClickInternal(View.java:7102) at android.view.View.access$3500(View.java:801) at android.view.View$PerformClick.run(View.java:27336) at android.os.Handler .handleCallback(Handler.java:883) 在 android.os.Handler.dispatchMessage(Handler.java:100) 在 android.os.Looper.loop(Looper.java:214) 在 android.app.ActivityThread.main(ActivityThread. java:7356) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit。主要(ZygoteInit.java:930)
With the safe call
I get null
as output通过safe call
我得到null
作为输出
Full code:完整代码:
MainActivity.class: MainActivity.class:
package my.example.package
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.GsonBuilder
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.*
import java.io.IOException
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Picasso.get().load("https://...../....../example.png").into(Viewer)
var PlayerName: String = ""
fun fetchJson() {
val url = "https://my.api.site/example/"
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()
println(body)
val gson = GsonBuilder().create()
val PlayerStats = gson.fromJson(body, PlayerStats::class.java)
println(PlayerStats)
}
override fun onFailure(call: Call, e: IOException) {
println("API execute failed")
}
})
}
buttonGO.setOnClickListener {
PlayerName = editText.text.toString()
fetchJson()
if (PlayerName == null || PlayerName.trim() == "") {
println("please input data, input cannot be blank")
} else {
Picasso.get().load("https://...../...../" + PlayerName + ".png")
.into(Viewer)
textView.setText(PlayerName).toString()
}
}
}
}
PlayerStats.class: PlayerStats.class:
package my.example.package
class PlayerStats(val username: String , val level: Double )
Replace this with your code:用您的代码替换它:
class MainActivity : AppCompatActivity() {
lateinit var playerStats: PlayerStats
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Picasso.get().load("https://...../....../example.png").into(Viewer)
var PlayerName: String = ""
fun fetchJson() {
val url = "https://my.api.site/example/"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
var mainHandler = Handler(this@MainActivity.getMainLooper())
override fun onResponse(call: Call, response: Response) {
mainHandler.post {
val body = response.body()?.string()
if (body == null) return@post
println(body)
val gson = GsonBuilder().create()
playerStats = gson.fromJson(body, PlayerStats::class.java)
println(playerStats)
// TODO Now you can access to your view and set every thing to textView
textView.text = playerStats.username
}
}
override fun onFailure(call: Call, e: IOException) {
println("API execute failed")
}
})
}
buttonGO.setOnClickListener {
PlayerName = editText.text.toString()
fetchJson()
if (PlayerName == null || PlayerName.trim() == "") {
println("please input data, input cannot be blank")
} else {
Picasso.get().load("https://...../...../" + PlayerName + ".png")
.into(Viewer)
textView.setText(PlayerName).toString()
}
}
}
} ```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.