如何解决openweathermap api json 齐射响应返回空
我的 API url 在浏览器中工作,但由于某种原因,json 对象的所有字段都返回为 null。我在清单中添加了必要的互联网权限,但不确定为什么我的对象在我的 api 请求结束时都是空的。这是我的代码:
private lateinit var requestQueue : RequestQueue
private lateinit var weather : JSONArray
private lateinit var currentWeather : JSONObject
private var id = 0
private lateinit var mainWeather : String
private lateinit var description : String
private var singleDayUrl = "https://api.openweathermap.org/data/2.5/weather?q=London&appid={apiKey}"
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container,MainFragment.newInstance())
.commitNow()
}
requestQueue = Volley.newRequestQueue(this)
val jsonObj : JsonObjectRequest = JsonObjectRequest(Request.Method.GET,singleDayUrl,null,Response.Listener<JSONObject> { response -> weather = response.getJSONArray("weather")
currentWeather = weather.getJSONObject(0)
id = currentWeather.getInt("id")
mainWeather = currentWeather.getString("main")
description = currentWeather.getString("description")},Response.ErrorListener() { /**/ })
requestQueue.add(jsonObj)
}
我正在使用以下导入:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.haacke.android_p3.ui.main.MainFragment
import android.util.Log;
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
当我在这个函数结束时调试时,所有的变量(天气、当前天气等...)都显示为空。事实上,我认为整个响应可能是空的。我的 logcat 什么也没显示。我做错了什么?
编辑:我为响应消息添加了一个 Log.i,唉,它什么也没显示:(
解决方法
我发现一切都显示为空的原因是我在请求函数之后直接设置了一个断点,而不是在侦听器本身内部。因此,当我到达初始断点时,听众还没有听到响应。通过在侦听器内设置断点,已听到响应,并且值不再为空。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。