具体代码如下
public class MainActivity extends AppCompatActivity {
private String path="http://172.17.29.120/localuser/loupengfei/kaoshi/student.xml";
private ListView lv;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
List<Bean> list= (List<Bean>) msg.obj;
lv.setAdapter(new MylistviewAdapter(MainActivity.this,list));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到控件id
lv= (ListView) findViewById(R.id.lv);
//得到数据
getdata();
}
public void getdata() {
new Thread(){
@Override
public void run() {
try {
URL url=new URL(path);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
//解析
XmlPullParser parser= Xml.newPullParser();
parser.setInput(new InputStreamReader(inputStream));
List<Bean> list=new ArrayList<Bean>();
int evenType=parser.getEventType();
Bean bean=null;
while(evenType!=XmlPullParser.END_DOCUMENT) {
switch (evenType) {
case XmlPullParser.START_TAG:
String name = parser.getName();
if ("student".equals(name)) {
//文档开始的时候创建
bean = new Bean();
//学号
bean.setXuehao(parser.getAttributeValue(0));
} else if ("name".equals(name)) {
bean.setName(parser.nextText());
} else if ("address".equals(name)) {
bean.setAddress(parser.nextText());
} else if ("phone".equals(name)) {
bean.setPhone(parser.nextText());
} else if ("tel".equals(name)) {
bean.setTel(parser.nextText());
} else if ("school".equals(name)) {
bean.setSchool(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
//标签结束时添加到集合
list.add(bean);
break;
}
//步幅
evenType=parser.next();
}
//发送
Message msg=Message.obtain();
msg.obj=list;
handler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}.start();
}
}