ANDROID_MARS学习笔记_S01原始版_020_Mp3player001_歌曲列表

一、项目设计

ANDROID_MARS学习笔记_S01原始版_020_Mp3player001_歌曲列表

ANDROID_MARS学习笔记_S01原始版_020_Mp3player001_歌曲列表

二、歌曲列表简介

1.利用java.net.HttpURLConnection以流的形式下载xml文件为String

2.自定义ContentHandler--》Mp3ListContentHandler

3.利用自定义的ContentHandler和javax.xml.parsers.SAXParserFactory生成org.xml.sax.XMLReader,用来处理下载的xml字符串,处理结果以List<Mp3Info>返回

4.以返回的List<Mp3Info>和布局文件创建android.widget.SimpleAdapter

5.最后在activity中调用setListAdapter(adapter),完成更新列表操作

二、代码
1.xml
(1)main.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:id="@+id/listLinearLayout"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<ListView android:id="@id/android:list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:drawSelectorOnTop="false"
android:scrollbars="vertical" />
</LinearLayout>
</LinearLayout>

(2)AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tony.mp3player"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Mp3ListActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

3.mp3info_item.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="1dip"
android:paddingBottom="1dip"
>
<TextView android:id="@+id/mp3Name"
android:layout_height="30dip"
android:layout_width="180dip"
android:textSize="10pt"/>
<TextView android:id="@+id/mp3Size"
android:layout_height="30dip"
android:layout_width="180dip"
android:textSize="10pt"/>
</LinearLayout>

2.java
(1)Mp3ListActivity.java

 package tony.mp3player;

 import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader; import tony.download.HttpDownloader;
import tony.model.Mp3Info;
import tony.xml.Mp3ListContentHandler;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleAdapter; @SuppressLint("NewApi")
public class Mp3ListActivity extends ListActivity {
private static final int UPDATE = 1;
private static final int ABOUT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
updateListView();
} /**
* 在用点击MENU按钮之后,会调用该方法,我们可以在这个方法当中加入自己的按钮控件
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, UPDATE, UPDATE, R.string.mp3list_update);
menu.add(0, ABOUT, ABOUT, R.string.mp3list_about);
return super.onCreateOptionsMenu(menu);
} /**
* 当菜单选项被选中时调用
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("onOptionsItemSelected--->ItemId="+item.getItemId());
switch (item.getItemId()) {
case UPDATE:
updateListView();
break;
case 2:
break;
default:
break;
}
return super.onOptionsItemSelected(item);
} private void updateListView() {
String xml = downloadXML("http://192.168.1.104:8080/mp3/resources.xml");
List<Mp3Info> infos = parse(xml);
SimpleAdapter adapter = buidSimpleAdapter(infos);
setListAdapter(adapter);
} private SimpleAdapter buidSimpleAdapter(List<Mp3Info> infos) {
// 生成一个List对象,并按照SimpleAdapter的标准,将mp3Infos当中的数据添加到List当中去
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String,String> map = null;
Mp3Info info = null;
for(Iterator it = infos.iterator() ; it.hasNext() ;) {
info = (Mp3Info) it.next();
map = new HashMap<String,String>();
map.put("mp3Name", info.getMp3Name());
map.put("mp3Size", info.getMp3Size());
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.mp3info_item,
new String[]{"mp3Name", "mp3Size"}, new int[]{R.id.mp3Name, R.id.mp3Size});
return adapter;
} private String downloadXML(String urlStr) {
HttpDownloader httpDownloader = new HttpDownloader();
String result = httpDownloader.download(urlStr);
return result;
} private List<Mp3Info> parse(String xml) {
SAXParserFactory spf = SAXParserFactory.newInstance();
List<Mp3Info> infos = new ArrayList<Mp3Info>();
try {
XMLReader reader = spf.newSAXParser().getXMLReader();
Mp3ListContentHandler handler = new Mp3ListContentHandler(infos);
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(xml)));
for(Iterator it = infos.iterator();it.hasNext();) {
Mp3Info info = (Mp3Info) it.next();
System.out.println(info);
}
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return infos;
}
}

(2)Mp3ListContentHandler.java

 package tony.xml;

 import java.util.List;

 import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; import tony.model.Mp3Info; public class Mp3ListContentHandler extends DefaultHandler { private List<Mp3Info> infos = null;
private Mp3Info mp3Info = null;
private String tagName = null; public Mp3ListContentHandler(List<Mp3Info> infos) {
super();
this.infos = infos;
} @Override
public void startDocument() throws SAXException {
super.startDocument();
} @Override
public void endDocument() throws SAXException {
super.endDocument();
} @Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
this.tagName = localName;
if(tagName.equals("resource")) {
mp3Info = new Mp3Info();
}
} @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals("resource")) {
infos.add(mp3Info);
}
tagName = "";
} @Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String temp = new String(ch, start, length);
if(tagName.equals("id"))
mp3Info.setId(temp);
else if(tagName.equals("mp3.name"))
mp3Info.setMp3Name(temp);
else if(tagName.equals("mp3.size"))
mp3Info.setMp3Size(temp);
else if(tagName.equals("lrc.name"))
mp3Info.setLrcName(temp);
else if(tagName.equals("lrc.size"))
mp3Info.setLrcSize(temp);
}
}

(3)HttpDownloader.java

 package tony.download;

 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; public class HttpDownloader { /**
* 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容
* 1.创建一个URL对象
* 2.通过URL对象,创建一个HttpURLConnection对象
* 3.得到InputStram
* 4.从InputStream当中读取数据
* @param urlStr
* @return
*/
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
// 创建一个URL对象
URL url = new URL(urlStr);
// 创建一个Http连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 使用IO流读取数据
buffer = new BufferedReader(new InputStreamReader(urlConn
.getInputStream()));
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

(4)

 package tony.model;

 public class Mp3Info {

     private String id,mp3Name,mp3Size,lrcName,lrcSize;

     public Mp3Info() {
super();
} public Mp3Info(String id, String mp3Name, String mp3Size, String lrcName,
String lrcSize) {
super();
this.id = id;
this.mp3Name = mp3Name;
this.mp3Size = mp3Size;
this.lrcName = lrcName;
this.lrcSize = lrcSize;
} @Override
public String toString() {
return "Mp3Info [id=" + id + ", mp3Name=" + mp3Name + ", mp3Size="
+ mp3Size + ", lrcName=" + lrcName + ", lrcSize=" + lrcSize
+ "]";
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getMp3Name() {
return mp3Name;
} public void setMp3Name(String mp3Name) {
this.mp3Name = mp3Name;
} public String getMp3Size() {
return mp3Size;
} public void setMp3Size(String mp3Size) {
this.mp3Size = mp3Size;
} public String getLrcName() {
return lrcName;
} public void setLrcName(String lrcName) {
this.lrcName = lrcName;
} public String getLrcSize() {
return lrcSize;
} public void setLrcSize(String lrcSize) {
this.lrcSize = lrcSize;
} }

四、运行结果

ANDROID_MARS学习笔记_S01原始版_020_Mp3player001_歌曲列表

上一篇:ASP.NET用户自定义控件配置


下一篇:ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER003_播放mp3