我正在尝试设置var json,但最后得到空指针。任何想法如何解决这一问题 ?还是Android新手
class Requester(activity: Activity) {
...
var json : Info? = null
...
fun getData (counter : Int) {
println("frist attemp"+json)// here it is null as it should be
var show = 5*counter
var url = "https://reqres.in/api/users?page=1&per_page=$show"
var 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 = GsonBuilder().create()
json = gson.fromJson(body,Info::class.java)//it should be init here
activity.runOnUiThread {
dataSize = json!!.total
val adapter = UsersAdapter(activity ,json!!,activity)
if(activity is MainActivity)
activity.recycler_View.adapter = adapter
}
isLoading=false
toast.cancel()
}
override fun onFailure(call: Call?, e: IOException?) {
activity.runOnUiThread {
val adapter = UsersAdapter(activity ,Info(0,0,0,0,
listOf(Data(0,"NO CONECTION","",""))),activity)
activity.recycler_View.adapter = adapter
Toast.makeText(activity,"Failed to connect", Toast.LENGTH_SHORT).show()
toast.cancel()
}
isLoading=false
}
})
println("end "+json)// here i get NULL any ideas why ?
}
}
课程信息:
class Info(val page: Int,
val per_page: Int,
val total: Int,
val total_pages: Int,
val data: List<Data>)
班级数据:
class Data(val id: Int,
val first_name: String,
val last_name: String,
val avatar: String)
UserActivity类:
class UserActivity : AppCompatActivity(){
var id : Int =0
val requester : Requester = Requester(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user)
id = intent.getIntExtra("id",0)
display()
}
private fun display() {
textView_ID_DEFINED.setText("$id")
requester.getData(id/3+1)
var info : Info? = requester.json
println("requester="+requester)
println("requester.info= "+requester.json)
if (info !=null){
for (i in 0..info.data.size){
if (id == info.data[i].id){
println("ahoj")
}
}
}
}
}
Stacktrace:
I /时间轴:时间轴:Activity_launch_request ID:com.example.android.zadanie时间:197846234 I / System.out:requester=com.example.android.zadanie.Requester@127852b requester.info = null I /时间轴:时间轴:Activity_idle ID:android.os.BinderProxy@5994e58时间:197846419 I / System.out:com.example.android.zadanie.Info@e380f1b中部
答案 0 :(得分:0)
当HTTP请求完成时,应该初始化json
变量(即fun onResponse
)的初始化位置。这意味着getData
在回调被实际调用之前之前结束,这就是为什么您得到null
的原因。
为什么您的回调被异步调用?好的,这就是enqueue
的实现方式,它的主要优点是它在一个单独的线程中运行HTTP请求,因此您的UI不会冻结。但是,在使用异步回调时,您必须考虑到您的代码可以在任何时间执行,即使您的应用程序不再处于前台(设想在应用程序运行时用户接听电话的情况)>