【发布时间】:2021-06-24 12:02:22
【问题描述】:
我的 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,唉,它什么也没显示 :(
【问题讨论】:
标签: json android-studio kotlin android-volley openweathermap