1. 程式人生 > >Android-通過網路獲取xml檔案使用pull解析得到伺服器中的資訊(新聞客戶端)

Android-通過網路獲取xml檔案使用pull解析得到伺服器中的資訊(新聞客戶端)

通過網路獲取xml檔案,使用pull解析該檔案得到伺服器中的資訊;

demo中使用了一個開源的圖片載入包,故上傳原始碼方便檢視;

效果圖:


步驟:

1.連線伺服器獲取xml檔案;

2.使用pull解析xml檔案存入實體物件中;

3.解析後將實體物件存入List集合中;

4.使用BaseAdapter,將List集合中中的資料顯示在listview中;

注意許可權的新增;

xml佈局檔案:

item_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.loopj.android.image.SmartImageView
        android:id="@+id/image"
        android:layout_width="90dp"
        android:layout_height="70dp"
        android:layout_alignBottom="@+id/tv_comment"
        android:layout_alignParentLeft="true"
        android:layout_margin="5dp"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image"
        android:singleLine="true"
        android:text="新聞標題"
        android:textSize="22sp" />


    <TextView
        android:id="@+id/tv_detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title"
        android:layout_toRightOf="@id/image"
        android:lines="2"
        android:text="新聞內容新聞內容新聞內容新聞內容新聞內容"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/tv_comment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/tv_detail"
        android:text="13833條評論"
        android:textColor="#ff0000" />

</RelativeLayout>

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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"
    tools:context="com.example.android07.MainActivity" >

    <ListView
        android:id="@+id/lisview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</RelativeLayout>

java檔案

News.java

package com.example.android07;

public class News {

	private String title;
	private String detail;
	private String comment;
	private String imageUrl;
	
	@Override
	public String toString() {
		return "News [title=" + title + ", detail=" + detail + ", comment="
				+ comment + ", imageUrl=" + imageUrl + "]";
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDetail() {
		return detail;
	}

	public void setDetail(String detail) {
		this.detail = detail;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public String getImageUrl() {
		return imageUrl;
	}

	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}
}

MainActivity.java
package com.example.android07;

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

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.image.SmartImageView;

public class MainActivity extends Activity {

	List<News> newsList;
	ListView listView;
	Handler handler;
	MyAdapter myAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.lisview);
		getNewsInfo();
		//建立介面卡例項
		myAdapter = new MyAdapter(this);
		//建立Handler例項
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				// 要保證在設定介面卡時,新聞xml檔案已經解析完畢了
				// 新增介面卡
				listView.setAdapter(myAdapter);
			}
		};
	}

	class MyAdapter extends BaseAdapter {

		Context context;
		LayoutInflater inflater;

		public MyAdapter(Context context) {
			this.context = context;
			inflater = LayoutInflater.from(context);
		}

		@Override
		// 得到模型層中元素的數量,用來確定listview需要有多少個條目
		public int getCount() {
			// TODO Auto-generated method stub
			return newsList.size();
		}

		@Override
		// 返回一個View物件,作為listview的條目顯示至介面
		public View getView(int position, View convertView, ViewGroup parent) {
			News news = newsList.get(position);
			ViewHolder viewHolder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_listview, null);
				viewHolder = new ViewHolder();
				// 把佈局檔案中所有元件的物件封裝至ViewHolder物件中
				viewHolder.St_image = (SmartImageView) convertView
						.findViewById(R.id.image);
				viewHolder.tv_title = (TextView) convertView
						.findViewById(R.id.tv_title);
				viewHolder.tv_detail = (TextView) convertView
						.findViewById(R.id.tv_detail);
				viewHolder.tv_commen = (TextView) convertView
						.findViewById(R.id.tv_comment);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			// 給新聞圖片imageview設定內容
			viewHolder.St_image.setImageUrl(news.getImageUrl());
			// 給三個文字框設定內容
			viewHolder.tv_title.setText(news.getTitle());
			viewHolder.tv_detail.setText(news.getDetail());
			viewHolder.tv_commen.setText(news.getComment());
			//返回填充的佈局item_listview
			return convertView;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		class ViewHolder {
			//條目的佈局檔案中有什麼元件,這裡就定義什麼屬性
			private SmartImageView St_image;
			private TextView tv_title;
			private TextView tv_detail;
			private TextView tv_commen;
		}

	}

	private void getNewsInfo() {
		Thread thread = new Thread() {
			@Override
			public void run() {
				super.run();
				Log.v("tag", "1111111111");
				String path = "http://192.168.47.25:8080/mytest/news.xml";
				try {
					URL url = new URL(path);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setRequestMethod("GET");
					conn.setConnectTimeout(5000);
					conn.setReadTimeout(5000);
//					conn.connect();
					//傳送http GET請求,獲取相應碼
					if (conn.getResponseCode() == 200) {
						InputStream is = conn.getInputStream();
						//使用pull解析器,解析這個流
						parseNewsXml(is);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		};
		thread.start();
	}

	private void parseNewsXml(InputStream is) {
		XmlPullParser xp = Xml.newPullParser();
		try {
			xp.setInput(is, "utf-8");
			//對節點的事件型別進行判斷,就可以知道當前節點是什麼節點
			int type = xp.getEventType();
			News news = null;
			while (type != XmlPullParser.END_DOCUMENT) {
				switch (type) {
				case XmlPullParser.START_TAG:
					if ("newslist".equals(xp.getName())) {
						newsList = new ArrayList<>();
					} else if ("news".equals(xp.getName())) {
						news = new News();
					} else if ("title".equals(xp.getName())) {
						String title = xp.nextText();
						news.setTitle(title);
					} else if ("detail".equals(xp.getName())) {
						String detail = xp.nextText();
						news.setDetail(detail);
					} else if ("comment".equals(xp.getName())) {
						String comment = xp.nextText();
						news.setComment(comment);
					} else if ("image".equals(xp.getName())) {
						String image = xp.nextText();
						news.setImageUrl(image);
					}
					break;
				case XmlPullParser.END_TAG:
					if ("news".equals(xp.getName())) {
						newsList.add(news);
					}
					break;
				default:
					break;
				}
				//解析完當前節點後,把指標移動至下一個節點,並返回它的事件型別
				type = xp.next();
			}
			// 發訊息,讓主執行緒設定listview的介面卡,如果訊息不需要攜帶資料,可以傳送空訊息
			handler.sendEmptyMessage(1);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

伺服器端中news.xml的檔案程式碼:
<?xml version="1.0" encoding="UTF-8" ?>
<newslist>
	<news>
		<title>新聞一</title>
		<detail>新聞一內容</detail>
		<comment>15687</comment>
		<image>http://192.168.47.25:8080/mytest/images/1.jpg</image>
	</news>
	<news>
		<title>新聞二</title>
		<detail>新聞二內容</detail>
		<comment>16359</comment>
		<image>http://192.168.47.25:8080/mytest/images/2.jpg</image>
	</news>
	<news>
		<title>新聞三</title>
		<detail>新聞三內容</detail>
		<comment>14112</comment>
		<image>http://192.168.47.25:8080/mytest/images/3.jpg</image>
	</news>
	<news>
		<title>新聞四</title>
		<detail>新聞四內容</detail>
		<comment>6427</comment>
		<image>http://192.168.47.25:8080/mytest/images/4.jpg</image>
	</news>
	<news>
		<title>新聞五</title>
		<detail>新聞五內容</detail>
		<comment>681</comment>
		<image>http://192.168.47.25:8080/mytest/images/5.jpg</image>
	</news>
</newslist>