溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android解析XML(PULL)展示到ListView

發(fā)布時間:2020-08-20 21:27:02 來源:腳本之家 閱讀:176 作者:qq_37278353 欄目:移動開發(fā)

Android解析XML展示到ListView運(yùn)行后的效果圖如下:

Android解析XML(PULL)展示到ListView

服務(wù)端的請求頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <a href="studentActiongetXML.action" rel="external nofollow" >獲取XML數(shù)據(jù)</a><br/>


</body>
</html>

服務(wù)端返回結(jié)果的頁面

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<students>
<c:forEach items="${students}" var="s">
 <student name="${s.name}">
  <sex>${s.sex}</sex>
 </student>
 </c:forEach>
</students>

服務(wù)端的Java代碼

package com.zking.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.zking.entity.Student;

public class StudentAction extends ActionSupport{

public String getXML() throws Exception {

 //查詢數(shù)據(jù)庫,獲取數(shù)據(jù)
 List<Student> students=new ArrayList<>();
 for (int i = 1; i <=20; i++) {
  Student student=new Student("小霜"+i, "女");
  students.add(student);
 }

 //將對象集合保存到請求域中
 ServletActionContext.getRequest().setAttribute("students", students);
 return "dataResult";
 } 
} 

服務(wù)端的配置文件(struts.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">
 <struts>
 <package name="myPackage" extends="struts-default">

  <action name="studentAction*" class="com.zking.action.StudentAction" method="{1}">
   <result name="dataResult">/dataResult.jsp</result>

  </action>
 </package>
 </struts>

服務(wù)端的運(yùn)行結(jié)果

Android解析XML(PULL)展示到ListView

Android (布局文件 activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
 android:layout_width="match_parent" android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:orientation="vertical"
 tools:context="com.example.g150825_android29_parsexml.MainActivity">

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="獲取XML"
 android:onClick="getXML"
 />
 <ListView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/lv_main_list"
 ></ListView>
</LinearLayout>

Android(Java代碼 MainActivity)

package com.example.g150825_android29_parsexml;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
 List<Student> studentList=new ArrayList<>();
 private ListView lv_main_list;
 private MyAdater myAdater;
 private ProgressDialog progressDialog;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 //實(shí)例化進(jìn)度條對話框
 progressDialog = new ProgressDialog(this);
 progressDialog.setMessage("正在拼命加載中.....");

 lv_main_list = (ListView) findViewById(R.id.lv_main_list);

 //實(shí)例化適配器
 //設(shè)置適配器
 myAdater = new MyAdater();
 lv_main_list.setAdapter(myAdater);
 }

 class MyAdater extends BaseAdapter{

 @Override
 public int getCount() {
  return studentList.size();
 }

 @Override
 public Object getItem(int i) {
  return studentList.get(i);
 }

 @Override
 public long getItemId(int i) {
  return i;
 }

 @Override
 public View getView(int i, View view, ViewGroup viewGroup) {
  LinearLayout linearLayout=new LinearLayout(MainActivity.this);
  linearLayout.setOrientation(LinearLayout.HORIZONTAL);

  TextView textViewName=new TextView(MainActivity.this);
  textViewName.setText(studentList.get(i).getName());

  TextView textViewSex=new TextView(MainActivity.this);
  textViewSex.setText(studentList.get(i).getSex());

  linearLayout.addView(textViewName);
  linearLayout.addView(textViewSex);

  return linearLayout;
 }
 }

 public void getXML(View view){
 new MyTask().execute();
 }
 class MyTask extends AsyncTask{
 private Student student;

 @Override
 protected void onPreExecute() {
  super.onPreExecute();
  progressDialog.show();
 }

 @Override
 protected Object doInBackground(Object[] objects) {
  //01.確定網(wǎng)絡(luò)數(shù)據(jù)
  String path="http://192.168.43.152:8080/G150825_S2SH/studentActiongetXML.action";

  try {
  //02.實(shí)例化URL
  URL url=new URL(path);
  //03.獲取連接對象
  HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
  //04.設(shè)置請求方式
  httpURLConnection.setRequestMethod("GET");
  //05.設(shè)置請求連接超時的時間(優(yōu)化)
  httpURLConnection.setConnectTimeout(5000);
  //06.獲取響應(yīng)碼(結(jié)果碼)
  int code=httpURLConnection.getResponseCode();
  if (code==200){
   //07.獲取服務(wù)器返回過來的數(shù)據(jù)
   InputStream is=httpURLConnection.getInputStream();
   //測試(打?。?   //緩沖字符流
//   BufferedReader br=new BufferedReader(new InputStreamReader(is));
//   String str=null;
//   while ((str=br.readLine())!=null){
//   Log.i("test",str);
//   }
   //解析XML(PULL)
   XmlPullParser xmlPullParser=Xml.newPullParser();
   xmlPullParser.setInput(is,"UTF-8");
   int type=xmlPullParser.getEventType();
   while (type!=XmlPullParser.END_DOCUMENT){
   switch (type){

    case XmlPullParser.START_TAG:
    //獲取開始標(biāo)簽
    String startTagName=xmlPullParser.getName();
    if ("student".equals(startTagName)){
     student = new Student();
     //獲取name屬性值
     String name=xmlPullParser.getAttributeValue(0);
     student.setName(name);
    }else if("sex".equals(startTagName)){
     //獲取sex的文本值
     String sex=xmlPullParser.nextText();
     student.setSex(sex);

    }

    break;
    case XmlPullParser.END_TAG:
    //獲取到結(jié)束標(biāo)簽的名字
    String endTagName=xmlPullParser.getName();
    if("student".equals(endTagName)){
     studentList.add(student);

    }

    break;
   }
   type=xmlPullParser.next();
   }
  }
  } catch (Exception e) {
  e.printStackTrace();
  }

  return null;
 }

 @Override
 protected void onPostExecute(Object o) {
  super.onPostExecute(o);
  //通知適配器發(fā)生改變
  myAdater.notifyDataSetChanged();
  progressDialog.cancel();

 }
 }
}

Android (實(shí)體類 Student)

package com.example.g150825_android29_parsexml;

public class Student {
 private String name;
 private String sex;
 public Student() {
 super();
 // TODO Auto-generated constructor stub
 }
 public Student(String name, String sex) {
 super();
 this.name = name;
 this.sex = sex;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getSex() {
 return sex;
 }
 public void setSex(String sex) {
 this.sex = sex;
 }
}

在清單文件中添加權(quán)限即可(AndroidManifest.xml)

 <!--添加網(wǎng)絡(luò)權(quán)限-->
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI