kotlin for android 之 xml格式数据解析与简单listview的使用
我在网上找了个yahoo提供的xml数据,我也不知是干什么用的,只是方便于我们学习。如图:修改我们之前的项目,MainActivity.kt文件:
package com.example.xinwei.httpproject
import android.annotation.SuppressLint
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getInternetData()
}
fun getInternetData(){
val url="https://query.yahooapis.com/v1/public/yql?q=show%20tables&diagnostics=true"
val myAsyncTask=MyAsyncTask()
myAsyncTask.execute(url)
}
@SuppressLint("StaticFieldLeak")
inner class MyAsyncTask : AsyncTask<String, String, String>() {
override fun onProgressUpdate(vararg values: String?) {
super.onProgressUpdate(*values)
}
override fun doInBackground(vararg p0: String?):String {
try {
val url=URL(p0)
val urlConnect=url.openConnection() as HttpURLConnection
urlConnect.connectTimeout=7000
urlConnect.requestMethod="GET"
urlConnect.readTimeout=7000
var inString=convertToString(urlConnect.inputStream)
var parsedData=parseXML(inString)
publishProgress(parsedData)
urlConnect.disconnect()
return parsedData
}catch (e:Exception){
e.printStackTrace()
}
return "网站连接失败"
}
private fun convertToString(inputStream: InputStream?): String {
var bufferedReader=BufferedReader(InputStreamReader(inputStream))
var allString=StringBuilder()
bufferedReader.forEachLine {
allString.append(it)
}
bufferedReader.close()
inputStream?.close()
return allString.toString()
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
idtext.text=result
}
private fun parseXML(result: String): String {
try {
var factory=XmlPullParserFactory.newInstance()
var xmlParser=factory.newPullParser()
xmlParser.setInput(StringReader(result))
var eventType=xmlParser.eventType
var str= ArrayList<String>()
while (eventType!=XmlPullParser.END_DOCUMENT){
var nodeName=xmlParser.name
when(eventType){
XmlPullParser.START_TAG->{
if ("table".equals(nodeName)){
str.add(xmlParser.nextText())
}
}
}
eventType=xmlParser.next()
}
return str.joinToString(" ")
}catch (e:Exception){
e.printStackTrace()
}
return ""
}
}
}
我在doInBackground里调用了我写的parseXML这个方法,来解析xml格式,为了省事我把进度条去掉了。这是解析完的效果图:
这里每条数据看起来很乱,我们给加个listview,就是列表就好了,修改activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xinwei.httpproject.MainActivity">
<ListView
android:id="@+id/idlist"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
修改MainActivity.kt文件:
package com.example.xinwei.httpproject
import android.annotation.SuppressLint
import android.content.Context
import android.os.AsyncTask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getInternetData()
}
fun getInternetData(){
val url="https://query.yahooapis.com/v1/public/yql?q=show%20tables&diagnostics=true"
val myAsyncTask=MyAsyncTask(this)
myAsyncTask.execute(url)
}
@SuppressLint("StaticFieldLeak")
inner class MyAsyncTask(val context:Context) : AsyncTask<String, String, String>() {
override fun onProgressUpdate(vararg values: String?) {
super.onProgressUpdate(*values)
}
override fun doInBackground(vararg p0: String?):String {
try {
val url=URL(p0)
val urlConnect=url.openConnection() as HttpURLConnection
urlConnect.connectTimeout=7000
urlConnect.requestMethod="GET"
urlConnect.readTimeout=7000
var inString=convertToString(urlConnect.inputStream)
var parsedData=parseXML(inString)
publishProgress(parsedData)
urlConnect.disconnect()
return parsedData
}catch (e:Exception){
e.printStackTrace()
}
return "网站连接失败"
}
private fun convertToString(inputStream: InputStream?): String {
var bufferedReader=BufferedReader(InputStreamReader(inputStream))
var allString=StringBuilder()
bufferedReader.forEachLine {
allString.append(it)
}
bufferedReader.close()
inputStream?.close()
return allString.toString()
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
var data=result!!.split(" ")
idlist.adapter=ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,data)
}
private fun parseXML(result: String): String {
try {
var factory=XmlPullParserFactory.newInstance()
var xmlParser=factory.newPullParser()
xmlParser.setInput(StringReader(result))
var eventType=xmlParser.eventType
var str= ArrayList<String>()
while (eventType!=XmlPullParser.END_DOCUMENT){
var nodeName=xmlParser.name
when(eventType){
XmlPullParser.START_TAG->{
if ("table".equals(nodeName)){
str.add(xmlParser.nextText())
}
}
}
eventType=xmlParser.next()
}
return str.joinToString(" ")
}catch (e:Exception){
e.printStackTrace()
}
return ""
}
}
}
我给MyAsyncTask构造器传了个上下文context,这是必须有的,然后就使用了一句话就做好了listview列表idlist.adapter=ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,data),效果图如下:
页:
[1]