JSONRequest成功后的Android更新视图

我正在构建一个Android应用程序(我正在使用Kotlin而不是JAVA,但是如果你能让我的Java方法很好),它应该使用OpenWeather API显示天气信息。 我已经设定了观点:

                         

然后我有另一个类负责提出请求并单独更改每个字段,如下所示:

 public fun getCityInfo(name: String){ val URI = String.format("http://api.openweathermap.org/data/2.5/weather?q=%s&appid=", name) Log.d("uri", URI) var cityName: String = "" queue.add(JsonObjectRequest( URI, null, { cityName = it.getString("name") var main = it.getJSONObject("main") var temp: Double = main.getDouble("temp") //getting the rest of the info //I save the info that I need in a class var currTemp = CurrentTemperature(temp,press,humidity,min,max,state,desc,icon) var city = City(name, currTemp) //then set each field individually var detailsview = (context as AppCompatActivity).findViewById(R.id.layDetails) as View (detailsview.findViewById(R.id.txtCity) as TextView).setText(city.name) (detailsview.findViewById(R.id.txtCurTemp) as TextView).setText(city.currTemp.curr.toString()) }, { Toast.makeText(context, "Failed to get weather", Toast.LENGTH_LONG).show() } 

但是我想要的是成功返回城市实例,然后在我的字段中有一些自动更新视图的绑定。

我怎样才能做到这一点?

根本不了解Kotlin,但是我会尽量用Java术语来解释。

重新定义您的方法接受作为回调到活动的排雷监听器。

 public fun getCityInfo(name: String, callback: Response.Listener) 

然后,你调用这个函数,传入这个闭包作为callback

 getCityInfo("Chicago", { var cityName = it.getString("name") var main = it.getJSONObject("main") var temp: Double = main.getDouble("temp") //getting the rest of the info var currTemp = CurrentTemperature(temp,press,humidity,min,max,state,desc,icon) var city = City(name, currTemp) setCity(city) // TODO: implement method within Activity }) 

注意一个增加的setCity 。 你需要实现这个来更新你拥有的任何视图。

现在,在其他类中,只需传递Activity中的响应侦听器即可

 queue.add(JsonObjectRequest( URI, null, callback, { ... } // error handle