2016-10-29 5 views
0

Я создаю приложение для Android (я использую Kotlin, а не JAVA, но если вы можете получить мне подход Java, это прекрасно), который должен показывать информацию о погоде с использованием API OpenWeather. Я уже установить вид:Android Update View после успеха JSONRequest

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_margin="@dimen/activity_horizontal_margin"> 
    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/layCity"> 
     <TextView 
      android:id="@+id/txtCity" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:text="PORTO" 
      android:textSize="25sp" 
      android:textStyle="bold"/> 
     <TextView 
      android:id="@+id/txtCountry" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:text="(PT)" 
      android:textSize="25sp"/> 
    </LinearLayout> 
    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/layTempDetail" 
     android:layout_below="@+id/layCity" 
     android:orientation="vertical"> 
     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/txtCurTemp" 
      android:text="20º" 
      android:textSize="40sp" 
      android:textStyle="bold" 
      android:layout_marginTop="20dp"/> 
     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/lblMinTemp" 
       android:text="Min:" 
       android:textStyle="bold" 
       android:textSize="20sp"/> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/txtMinTemp" 
       android:text="10º" 
       android:textSize="20sp"/> 
     </LinearLayout> 
     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/lblMaxTemp" 
       android:text="Max:" 
       android:textStyle="bold" 
       android:textSize="20sp"/> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/txtMaxTemp" 
       android:text="30º" 
       android:textSize="20sp"/> 
     </LinearLayout> 
     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/lblPressure" 
       android:text="Pressure:" 
       android:textStyle="bold" 
       android:textSize="20sp"/> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/txtPressure" 
       android:text="100" 
       android:textSize="20sp"/> 
     </LinearLayout> 
     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/lblHumidity" 
       android:text="Humidity:" 
       android:textStyle="bold" 
       android:textSize="20sp"/> 
      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/txtHumidity" 
       android:text="30%" 
       android:textSize="20sp"/> 
     </LinearLayout> 
    </LinearLayout> 
</RelativeLayout> 

Тогда у меня есть еще один класс, ответственный, чтобы сделать запрос и изменить каждое поле по отдельности, как это:

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() 
       } 

Но то, что я хотел, чтобы вернуть экземпляр города на успех , то у меня есть какая-то привязка в моих полях, которая автоматически обновляет представление.

Как я могу это достичь?

+0

Почему у вас есть отдельный класс, чтобы сделать запрос? –

+0

Кроме того, волейбол не обновляется автоматически или не привязывается к каким-либо представлениям, если вы не сообщите об этом. Например, вы сделали это в 'setText (city.name)'. Не совсем уверен, что я вижу необходимость в 'var city' –

+0

@ cricket_007 только по причине организации. не более того. Я новичок в Android, так что я хочу знать, если есть способ обновить экземпляр, скажем, тогда обновление обновляется –

ответ

1

Не знаю Kotlin, но я попытаюсь объяснить достаточно, используя термины Java.

Переопределите свой метод, чтобы принять слушателя Volley в качестве обратного вызова активности.

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

Затем вы вызываете эту функцию, передавая в этом закрытия в этом 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. Вам нужно будет реализовать это, чтобы обновить все виды, которые у вас есть.

Теперь, в этом другом классе, просто передать слушателю ответа от активности

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

Мой вопрос в том, как можно Я привязываю эти поля экземпляра города к полям «TextView» в представлении? –

+0

'(findViewById (R.id.txtCity) как TextView) .setText (city.name)' ... Правильно? –

+0

Если вы пытаетесь спросить об этой библиотеке привязки данных, я не могу с этим поделать. https://developer.android.com/topic/libraries/data-binding/index.html –

Смежные вопросы