一个实例学习Kotlin 开发 Android App 的全过程(内有代码)

时间:2025-01-30 11:13:48

object Utility {

   //  解析和处理服务器返回的省级数据

   fun handleProvinceResponse(response: String): List {

      var provinces = mutableListOf ()

      if (!(response)) {

          try {

             //  将JSON数组转换为Kotlin数组形式      

             val allProvinces = JSONArray(response)

             //  对数组循环处理,每一次循环都会创建一个Province对象

             for (i in 0..() - 1) {

                val provinceObject = (i)

                val province = Province(provinceName = 

                ("name"),proinceCode = provinceObje  

                ("id"))

                (, province)

             }

         } catch (e: JSONException) {

             ()

         }

      }

      return provinces

   }

   //  解析和处理服务器返回的市级数据

   fun handleCityResponse(response: String, provinceCode: String): List {

      var cities = mutableListOf ()

      if (!(response)) {

         try {

             val allCities = JSONArray(response)

             for (i in 0..() - 1) {

                val cityObject = (i)

                val city = City(cityName = ("name"),cityCode  

                = ("id"),provinceCode = provinceCode)

                (city)

             }

         } catch (e: JSONException) {

             ()

         }

     }

     return cities

   }

   //  解析和处理服务器返回的县区级数据

   fun handleCountyResponse(response: String, cityCode: String): List {

      var counties = mutableListOf ()

      if (!(response)) {

          try {

             val allCounties = JSONArray(response)

             for (i in 0..() - 1) {

                 val countyObject = (i)

                 val county = County(countyName = ("name"), countyCode = ("id"),cityCode = cityCode)

                 (county)

             }

         } catch (e: JSONException) {

             ()

         }

     }

     return counties

   }

   //  将返回的JSON数据解析成Weather实体类

   fun handleWeatherResponse(response: String): Weather? {

      try {

         val jsonObject = JSONObject(response)

         val jsonArray = ("HeWeather")

         val weatherContent = (0).toString()

         return Gson().fromJson(weatherContent, Weather::)

      } catch (e: Exception) {

         ()

      }

      return null

   }

}