ANDROID_MARS学习笔记_S01原始版_011_XML

一、代码

1.xml
(1)main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent"
 6     >
 7 <Button
 8     android:id="@+id/parseButton"
 9     android:layout_width="fill_parent" 
10     android:layout_height="wrap_content" 
11     android:text="开始解析XML"
12     />
13 </LinearLayout>

 

(2)AndroidManifest.xml.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.s01_original_e20_xml"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="21" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name=".XMLActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21 
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25     </application>
26      <uses-permission android:name="android.permission.INTERNET"/>
27 </manifest>

 

2.java
(1)XMLActivity.java

 1 package com.example.s01_original_e20_xml;
 2 
 3 import java.io.StringReader;
 4 
 5 import javax.xml.parsers.SAXParserFactory;
 6 
 7 import org.xml.sax.InputSource;
 8 import org.xml.sax.XMLReader;
 9 
10 import android.app.Activity;
11 import android.os.Bundle;
12 import android.view.View;
13 import android.view.View.OnClickListener;
14 import android.widget.Button;
15 
16 import com.example.s01_original_e20_xml.util.HttpDownloader;
17 
18 public class XMLActivity extends Activity {
19     /** Called when the activity is first created. */
20     private Button parseButton ;
21     @Override
22     public void onCreate(Bundle savedInstanceState) {
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.main);
25         parseButton = (Button)findViewById(R.id.parseButton);
26         parseButton.setOnClickListener(new ParseButtonListener());
27     }
28     
29     class ParseButtonListener implements OnClickListener{
30 
31         @Override
32         public void onClick(View v) {
33             HttpDownloader hd = new HttpDownloader();
34             String resultStr = hd.download("http://192.168.1.104:8080/goods/test.xml");
35             System.out.println(resultStr);
36             try{
37                 //创建一个SAXParserFactory
38                 SAXParserFactory factory = SAXParserFactory.newInstance();
39                 XMLReader reader = factory.newSAXParser().getXMLReader();
40                 //为XMLReader设置内容处理器
41                 reader.setContentHandler(new MyContentHandler());
42                 //开始解析文件
43                 reader.parse(new InputSource(new StringReader(resultStr)));
44             }
45             catch(Exception e){
46                 e.printStackTrace();
47             }
48         }
49         
50     }
51 }

 

(2)MyContentHandler.java

 1 package com.example.s01_original_e20_xml;
 2 
 3 import org.xml.sax.Attributes;
 4 import org.xml.sax.SAXException;
 5 import org.xml.sax.helpers.DefaultHandler;
 6 
 7 public class MyContentHandler extends DefaultHandler {
 8     String hisname, address, money, sex, status;
 9     String tagName;
10 
11     public void startDocument() throws SAXException {
12         System.out.println("````````begin````````");
13     }
14 
15     public void endDocument() throws SAXException {
16         System.out.println("````````end````````");
17     }
18 
19     //localName不带前缀,qName带前缀
20     public void startElement(String namespaceURI, String localName,
21             String qName, Attributes attr) throws SAXException {
22         tagName = localName;
23         if (localName.equals("worker")) {
24             //获取标签的全部属性
25             for (int i = 0; i < attr.getLength(); i++) {
26                 System.out.println(attr.getLocalName(i) + "=" + attr.getValue(i));
27             }
28         }
29     }
30 
31     public void endElement(String namespaceURI, String localName, String qName)
32             throws SAXException {
33         //在workr标签解析完之后,会打印出所有得到的数据
34         tagName = "";
35         if (localName.equals("worker")) {
36             this.printout();
37         }
38     }
39     public void characters(char[] ch, int start, int length)
40             throws SAXException {
41         if (tagName.equals("name"))
42             hisname = new String(ch, start, length);
43         else if (tagName.equals("sex"))
44             sex = new String(ch, start, length);
45         else if (tagName.equals("status"))
46             status = new String(ch, start, length);
47         else if (tagName.equals("address"))
48             address = new String(ch, start, length);
49         else if (tagName.equals("money"))
50             money = new String(ch, start, length);
51     }
52 
53     private void printout() {
54         System.out.print("name: ");
55         System.out.println(hisname);
56         System.out.print("sex: ");
57         System.out.println(sex);
58         System.out.print("status: ");
59         System.out.println(status);
60         System.out.print("address: ");
61         System.out.println(address);
62         System.out.print("money: ");
63         System.out.println(money);
64         System.out.println();
65     }
66 
67 }

 

(3)HttpDownloader.java

 1 package com.example.s01_original_e20_xml.util;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.File;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.InputStreamReader;
 8 import java.net.HttpURLConnection;
 9 import java.net.MalformedURLException;
10 import java.net.URL;
11 
12 
13 public class HttpDownloader {
14     private URL url = null;
15 
16     /**
17      * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容
18      * 1.创建一个URL对象
19      * 2.通过URL对象,创建一个HttpURLConnection对象
20      * 3.得到InputStram
21      * 4.从InputStream当中读取数据
22      * @param urlStr
23      * @return
24      */
25     public String download(String urlStr) {
26         StringBuffer sb = new StringBuffer();
27         String line = null;
28         BufferedReader buffer = null;
29         try {
30             // 创建一个URL对象
31             url = new URL(urlStr);
32             // 创建一个Http连接
33             HttpURLConnection urlConn = (HttpURLConnection) url
34                     .openConnection();
35             // 使用IO流读取数据
36             buffer = new BufferedReader(new InputStreamReader(urlConn
37                     .getInputStream()));
38             while ((line = buffer.readLine()) != null) {
39                 sb.append(line);
40             }
41         } catch (Exception e) {
42             e.printStackTrace();
43         } finally {
44             try {
45                 buffer.close();
46             } catch (Exception e) {
47                 e.printStackTrace();
48             }
49         }
50         return sb.toString();
51     }
52 
53     /**
54      * 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
55      */
56     public int downFile(String urlStr, String path, String fileName) {
57         InputStream inputStream = null;
58         try {
59             FileUtils fileUtils = new FileUtils();
60             
61             if (fileUtils.isFileExist(path + fileName)) {
62                 return 1;
63             } else {
64                 inputStream = getInputStreamFromUrl(urlStr);
65                 File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream);
66                 if (resultFile == null) {
67                     return -1;
68                 }
69             }
70         } catch (Exception e) {
71             e.printStackTrace();
72             return -1;
73         } finally {
74             try {
75                 inputStream.close();
76             } catch (Exception e) {
77                 e.printStackTrace();
78             }
79         }
80         return 0;
81     }
82 
83     /**
84      * 根据URL得到输入流
85      * 
86      * @param urlStr
87      * @return
88      * @throws MalformedURLException
89      * @throws IOException
90      */
91     public InputStream getInputStreamFromUrl(String urlStr)
92             throws MalformedURLException, IOException {
93         url = new URL(urlStr);
94         HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
95         InputStream inputStream = urlConn.getInputStream();
96         return inputStream;
97     }
98 }

 

(4)FileUtils.java

 1 package com.example.s01_original_e20_xml.util;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 
 9 import android.os.Environment;
10 
11 public class FileUtils {
12     private String SDPATH;
13 
14     public String getSDPATH() {
15         return SDPATH;
16     }
17     public FileUtils() {
18         //得到当前外部存储设备的目录
19         // /SDCARD
20         SDPATH = Environment.getExternalStorageDirectory() + "/";
21     }
22     /**
23      * 在SD卡上创建文件
24      * 
25      * @throws IOException
26      */
27     public File creatSDFile(String fileName) throws IOException {
28         File file = new File(SDPATH + fileName);
29         file.createNewFile();
30         return file;
31     }
32     
33     /**
34      * 在SD卡上创建目录
35      * 
36      * @param dirName
37      */
38     public File creatSDDir(String dirName) {
39         File dir = new File(SDPATH + dirName);
40         dir.mkdir();
41         return dir;
42     }
43 
44     /**
45      * 判断SD卡上的文件夹是否存在
46      */
47     public boolean isFileExist(String fileName){
48         File file = new File(SDPATH + fileName);
49         return file.exists();
50     }
51     
52     /**
53      * 将一个InputStream里面的数据写入到SD卡中
54      */
55     public File write2SDFromInput(String path,String fileName,InputStream input){
56         File file = null;
57         OutputStream output = null;
58         try{
59             creatSDDir(path);
60             file = creatSDFile(path + fileName);
61             output = new FileOutputStream(file);
62             byte buffer [] = new byte[4 * 1024];
63             while((input.read(buffer)) != -1){
64                 output.write(buffer);
65             }
66             output.flush();
67         }
68         catch(Exception e){
69             e.printStackTrace();
70         }
71         finally{
72             try{
73                 output.close();
74             }
75             catch(Exception e){
76                 e.printStackTrace();
77             }
78         }
79         return file;
80     }
81 
82 }

PS:在HttpDownLoader.java的buffer = new BufferedReader(new InputStreamReader(urlConn .getInputStream()));,返回的buffer为空,不知原因

A:那是因为新的sdk不允许在main线程里访问网络,否则会抛android.os.NetworkOnMainThreadException,解决方法:http://www.2cto.com/kf/201402/281526.html

1 在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码
2 
3  
4 
5 if (android.os.Build.VERSION.SDK_INT > 9) {
6     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
7     StrictMode.setThreadPolicy(policy);
8 }

 

posted @ 2016-02-15 18:53  shamgod  阅读(145)  评论(0编辑  收藏  举报
haha