Android 在JsonObjectRequest之后返回函数中的对象
我是android开发新手,我的代码有问题。我试图解析json中的数据,将信息放入一个对象中,然后从函数返回 我的代码:Android 在JsonObjectRequest之后返回函数中的对象,android,android-studio,kotlin,Android,Android Studio,Kotlin,我是android开发新手,我的代码有问题。我试图解析json中的数据,将信息放入一个对象中,然后从函数返回 我的代码: data class AccountInfo ( var username: String, var bio: String, var avatar: String, var cover: String, var created: Long, var reputation: Double ) fun getAccountIn
data class AccountInfo (
var username: String,
var bio: String,
var avatar: String,
var cover: String,
var created: Long,
var reputation: Double
)
fun getAccountInfo(accessToken: String): AccountInfo {
var info = AccountInfo("username", "", "", "", 0, 0.0)
val jsonObjectRequest: JsonObjectRequest = object : JsonObjectRequest(Method.GET, "https://api.imgur.com/3/account/me", null, Response.Listener { response ->
Log.e(HomeFragment.TAG, "got $response")
try {
val data = JSONObject(response.toString())
val items = data.getJSONObject("data")
Log.e(HomeFragment.TAG, "username=" + items.getString("url"))
info.username = items.getString("url")
Log.e(HomeFragment.TAG, "username second=" + info.username)
info.bio = items.getString("bio")
info.avatar = items.getString("avatar")
info.cover = items.getString("cover")
info.created = items.getLong("created")
info.reputation = items.getDouble("reputation")
} catch (e: JSONException) {
Log.e(HomeFragment.TAG, "Parsing error: " + e.message)
}
}, Response.ErrorListener { error ->
Log.e(HomeFragment.TAG, "Response error: " + error.message)
}) {
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers["Authorization"] = "Bearer ${accessToken}"
headers["User-Agent"] = "epicture"
return headers
}
}
// Adding request to request queue
AppController.instance?.addToRequestQueue(jsonObjectRequest)
Log.e(HomeFragment.TAG, "username last=" + info.username)
return info
}
数据类AccountInfo(
var用户名:String,
var-bio:String,
var阿凡达:字符串,
变量覆盖:字符串,
创建变量:Long,
var声誉:双
)
有趣的getAccountInfo(accessToken:String):AccountInfo{
var info=AccountInfo(“用户名”、“0”、“0”、“0.0”)
val jsonObjectRequest:jsonObjectRequest=object:jsonObjectRequest(Method.GET)https://api.imgur.com/3/account/me,null,Response.Listener{Response->
Log.e(HomeFragment.TAG,“got$response”)
试一试{
val data=JSONObject(response.toString())
val items=data.getJSONObject(“数据”)
Log.e(HomeFragment.TAG,“username=“+items.getString(“url”))
info.username=items.getString(“url”)
Log.e(HomeFragment.TAG,“username second=“+info.username”)
info.bio=items.getString(“bio”)
info.avatar=items.getString(“avatar”)
info.cover=items.getString(“cover”)
info.created=items.getLong(“已创建”)
info.reputation=items.getDouble(“声誉”)
}捕获(e:JSONException){
Log.e(homepragment.TAG,“解析错误:+e.message”)
}
},Response.ErrorListener{error->
Log.e(HomeFragment.TAG,“响应错误:+错误.消息)
}) {
@抛出(AuthFailureError::类)
覆盖有趣的getHeaders():映射{
val headers=HashMap()
标头[“授权”]=“承载${accessToken}”
标题[“用户代理”]=“epicture”
返回标题
}
}
//将请求添加到请求队列
AppController.instance?.addToRequestQueue(jsonObjectRequest)
Log.e(HomeFragment.TAG,“username last=“+info.username”)
返回信息
}
问题是该函数总是返回默认的初始化对象(例如用户名为“username”),而不是在我的JsonObjectRequest中解析的字符串,即使解析正在工作(日志是正确的)
如果您有任何帮助或想法,谢谢 您应该等到JsonObjectRequest完成并从服务器返回结果,然后您得到了结果,您在响应中得到了结果。Listener回调,但您返回的info对象没有更新。 使用异步等待或挂起函数从服务器获取信息,然后返回信息 更新: 代码如下:
fun getAccountInfo(
accessToken: String,
onSuccess: (account: AccountInfo) -> Unit,
onError: (e: Exception) -> Unit
) {
val jsonObjectRequest: JsonObjectRequest = object : JsonObjectRequest(
Method.GET,
"https://api.imgur.com/3/account/me",
null,
Response.Listener { response ->
try {
val data = JSONObject(response.toString())
val items = data.getJSONObject("data")
val info = AccountInfo(
username = items.getString("url"),
bio = items.getString("bio"),
avatar = items.getString("avatar"),
cover = items.getString("cover"),
created = items.getLong("created"),
reputation = items.getDouble("reputation")
)
onSuccess.invoke(info) // request success so call this
} catch (e: JSONException) {
onError.invoke(e)
}
},
Response.ErrorListener { error ->
onError.invoke(error)
}) {
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers["Authorization"] = "Bearer $accessToken"
headers["User-Agent"] = "epicture"
return headers
}
}
AppController.instance?.addToRequestQueue(jsonObjectRequest)
}
即使我做了:doAsync{var info=Imgur.getAccountInfo(parameters.second.accessToken)val text:TextView=root.findViewById(R.id.TextView_account)作为TextView text.text=info.username;}.execute(),我也有相同的结果。info.username仍然是“username”
getAccountInfo("access token",
onSuccess = {
// todo show info in UI
Log.d(TAG, "onCreate: onSuccess : $it")
},
onError = {
// toast error or show custom error view
Log.e(TAG, "onCreate: onError: ", it)
}
)