0
我刚开始学习Kotlin,并试图使用Kotlin创建我的第一个Android应用程序。 我有一个基于Restful API构建的webservice,它为我返回一个json数组,像下图所示。Kotlin应用程序不显示我的json数组
我科特林代码显示通过GSON库JSON数组!
class MainActivity : AppCompatActivity() {
val TAG:String="TipCalculatorActivity"
var adapter:ArrayAdapter<Category>?=null
var dsSP: MutableList<Category> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
adapter=ArrayAdapter(this,android.R.layout.simple_list_item_1,dsSP)
lvCategory.adapter=adapter
}
override fun onResume() {
super.onResume()
var task=CategoryTask()
task.execute()
}
inner class CategoryTask:AsyncTask<Void, Void, MutableList<Category>>() {
override fun onPostExecute(result: MutableList<Category>?)
{
super.onPostExecute(result)
dsSP.clear()
dsSP.addAll(result!!)
}
override fun doInBackground(vararg p0: Void?): MutableList<Category>
{
var dsFromServer:MutableList<Category> = mutableListOf()
try {
var url:URL=URL("192.168.31.86/shop/api/category")
var conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.requestMethod="GET"
conn.addRequestProperty("content-type","application/json;charset:UTF-8")
var isr= InputStreamReader(conn.getInputStream(), "UTF-8")
var gson=Gson()
dsFromServer=gson.fromJson(isr,object:TypeToken<MutableList<Category>>(){}.type)
isr.close()
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return dsFromServer
}
override fun onPreExecute()
{
super.onPreExecute()
dsSP.clear()
}
}
}
当然,我宣布JSON阵列的所有属性另一个类,酷似web服务
那么,'ex.printStackTrace()'会被执行吗? –
也许'gson'不能创建'MutableList',因为它是一个接口。你有没有尝试'List',因为gson也支持java。 –
尝试在'onPostExecute'结尾添加'adapter !!。notifyDataSetChanged()' –