从网络上加载XML资源,其中包括图片,我们要做的解析XML里面的数据,并且把图片缓存到本地一个cache目录里面,并且用一个自定义的Adapter去填充到LIs

从网络上加载XML资源,其中包括图片,我们要做的解析XML里面的数据,并且把图片缓存到本地一个cache目录里面,并且用一个自定义的Adapter去填充到LIstView:
对象类

?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Contact {
         int id;
         String image;
         String name;
         
         public Contact() {
                super ();
         }
         public Contact( int id, String image, String name) {
                this .id = id;
                this .image = image;
                this .name = name;
         }
         public int getId() {
                return id;
         }
         public void setId( int id) {
                this .id = id;
         }
         public String getImage() {
                return image;
         }
         public void setImage(String image) {
                this .image = image;
         }
         public String getName() {
                return name;
         }
         public void setName(String name) {
                this .name = name;
         }
         
}


service类

?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public class ContactService {
 
         /*
          * 从服务器上获取数据
          */
         public List<Contact> getContactAll() throws Exception {
                List<Contact> contacts = null;
                String Parth = "http://10.0.2.2:8080/AsyncTaskTest/list.xml";
                URL url = new URL(Parth);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(30000);
                conn.setReadTimeout(30000);
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                         InputStream is = conn.getInputStream();
                         // 这里获取数据直接放在XmlPullParser里面解析
                         contacts = xmlParser(is);
                         return contacts;
                } else {
                         return null;
                }
         }
 
         // 这里并没有下载图片下来,而是把图片的地址保存下来了
         private List<Contact> xmlParser(InputStream is) throws Exception {
                List<Contact> contacts = null;
                Contact contact = null;
                XmlPullParser parser = Xml.newPullParser();
                parser.setInput(is, "UTF-8");
                int eventType = parser.getEventType();
                while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) {
                         switch (eventType) {
                         case XmlPullParser.START_TAG:
                                 if (parser.getName().equals("contacts")) {
                                        contacts = new ArrayList<Contact>();
                                 } else if (parser.getName().equals("contact")) {
                                        contact = new Contact();
                                        contact.setId(Integer.valueOf(parser.getAttributeValue(0)));
                                 } else if (parser.getName().equals("name")) {
                                        contact.setName(parser.nextText());
                                 } else if (parser.getName().equals("image")) {
                                        contact.setImage(parser.getAttributeValue(0));
                                 }
                                 break;
 
                         case XmlPullParser.END_TAG:
                                 if (parser.getName().equals("contact")) {
                                        contacts.add(contact);
                                 }
                                 break;
                         }
                }
                return contacts;
         }
 
         /*
          * 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片
          * 这里的path是图片的地址
          */
         public Uri getImageURI(String path, File cache) throws Exception {
                String name = MD5.getMD5(path) + path.substring(path.lastIndexOf( "." ));
                File file = new File(cache, name);
                // 如果图片存在本地缓存目录,则不去服务器下载
                if (file.exists()) {
                         return Uri.fromFile(file); //Uri.fromFile(path)这个方法能得到文件的URI
                } else {
                         // 从网络上获取图片
                         URL url = new URL(path);
                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                         conn.setConnectTimeout( 5000 );
                         conn.setRequestMethod( "GET" );
                         conn.setDoInput( true );
                         if (conn.getResponseCode() == 200 ) {
 
                                 InputStream is = conn.getInputStream();
                                 FileOutputStream fos = new FileOutputStream(file);
                                 byte [] buffer = new byte [ 1024 ];
                                 int len = 0 ;
                                 while ((len = is.read(buffer)) != - 1 ) {
                                        fos.write(buffer, 0 , len);
                                 }
                                 is.close();
                                 fos.close();
                                 // 返回一个URI对象
                                 return Uri.fromFile(file);
                         }
                }
                return null ;
         }
}


自定义Adapter

?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class ImageAdapter extends BaseAdapter {
 
         protected static final int SUCCESS_GET_IMAGE = 0 ;
         private Context context;
         private List<Contact> contacts;
         private File cache;
         private LayoutInflater mInflater;
 
         // 自己定义的构造函数
         public ImageAdapter(Context context, List<Contact> contacts, File cache) {
                this .context = context;
                this .contacts = contacts;
                this .cache = cache;
 
                mInflater = (LayoutInflater) context
                                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         }
 
         @Override
         public int getCount() {
                return contacts.size();
         }
 
         @Override
         public Object getItem( int position) {
                return contacts.get(position);
         }
 
         @Override
         public long getItemId( int position) {
                return position;
         }
 
         @Override
         public View getView( int position, View convertView, ViewGroup parent) {
                // 1获取item,再得到控件
                // 2 获取数据
                // 3绑定数据到item
                View view = null ;
                if (convertView != null ) {
                         view = convertView;
                } else {
                         view = mInflater.inflate(R.layout.item, null );
                }
 
                ImageView iv_header = (ImageView) view.findViewById(R.id.imageView);
                TextView tv_name = (TextView) view.findViewById(R.id.textView);
 
                Contact contact = contacts.get(position);
                 
                // 异步的加载图片 (线程池 + Handler ) ---> AsyncTask
                asyncloadImage(iv_header, contact.image);
                 
                tv_name.setText(contact.name);
 
                return view;
         }
         
         private void asyncloadImage(ImageView iv_header, String path) {
                ContactService service = new ContactService();
                AsyncImageTask task = new AsyncImageTask(service, iv_header);
                task.execute(path);
         }
 
         private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> {
 
                private ContactService service;
                private ImageView iv_header;
 
                public AsyncImageTask(ContactService service, ImageView iv_header) {
                         this .service = service;
                         this .iv_header = iv_header;
                }
 
                // 后台运行的子线程子线程
                @Override
                protected Uri doInBackground(String... params) {
                         try {
                                 return service.getImageURI(params[ 0 ], cache);
                         } catch (Exception e) {
                                 e.printStackTrace();
                         }
                         return null ;
                }
 
                // 这个放在在ui线程中执行
                @Override
                protected void onPostExecute(Uri result) {
                         super .onPostExecute(result);
                         // 完成图片的绑定
                         if (iv_header != null && result != null ) {
                                 iv_header.setImageURI(result);
                         }
                }
         }
}
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class MainActivity extends Activity {
        protected static final int SUCCESS_GET_CONTACT = 0 ;
        private ListView mListView;
        private ImageAdapter mAdapter;
        private File cache;
         
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         
         mListView = (ListView) findViewById(R.id.listView);
         
         //创建缓存目录,系统一运行就得创建缓存目录的,
         cache = new File(Environment.getExternalStorageDirectory(), "cache" );
         
         if (!cache.exists()){
                cache.mkdirs();
         }
         
         //获取数据,主UI线程是不能做耗时操作的,所以启动子线程来做
         new Thread(){
                public void run() {
                        ContactService service = new ContactService();
                        List<Contact> contacts = null ;
                                try {
                                        contacts = service.getContactAll();
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                                //子线程通过Message对象封装信息,并且用初始化好的,
                                //Handler对象的sendMessage()方法把数据发送到主线程中,从而达到更新UI主线程的目的
                        Message msg = new Message();
                        msg.what = SUCCESS_GET_CONTACT;
                        msg.obj = contacts;
                        mHandler.sendMessage(msg);
                };
         }.start();
    }
     
    private Handler mHandler = new Handler(){
                public void handleMessage(android.os.Message msg) {
                        if (msg.what == SUCCESS_GET_CONTACT){
                                List<Contact> contacts = (List<Contact>) msg.obj;
                                mAdapter = new ImageAdapter(getApplicationContext(),contacts,cache);
                                mListView.setAdapter(mAdapter);
                        }
                };
        };
     
    @Override
    protected void onDestroy() {
            super .onDestroy();
            //清空缓存
            File[] files = cache.listFiles();
            for (File file :files){
                    file.delete();
            }
            cache.delete();
    }
}


务器xml文件

?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
<?xml version= "1.0" encoding= "UTF-8" ?>
<contacts>
         <contact id= "1" >
                <name>图标 1 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/1.png" />
         </contact>
         <contact id= "2" >
                <name>图标 2 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/2.png" />
         </contact>
         <contact id= "3" >
                <name>图标 3 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/3.png" />
         </contact>
         <contact id= "4" >
                <name>图标 4 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/4.png" />
         </contact>
         <contact id= "5" >
                <name>图标 5 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/5.png" />
         </contact>
         <contact id= "6" >
                <name>图标 6 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/6.png" />
         </contact>
         <contact id= "7" >
                <name>图标 7 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/7.png" />
         </contact>
         <contact id= "8" >
                <name>图标 8 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/8.png" />
         </contact>
         <contact id= "9" >
                <name>图标 9 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/9.png" />
         </contact>
         <contact id= "10" >
                <name>图标 10 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/10.png" />
         </contact>
         <contact id= "11" >
                <name>图标 11 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/11.png" />
         </contact>
         <contact id= "12" >
                <name>图标 12 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/12.png" />
         </contact>
 
         <contact id= "13" >
                <name>图标 13 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/13.png" />
         </contact>
         <contact id= "14" >
                <name>图标 14 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/14.png" />
         </contact>
         <contact id= "15" >
                <name>图标 15 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/15.png" />
         </contact>
         <contact id= "16" >
                <name>图标 16 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/16.png" />
         </contact>
         <contact id= "17" >
                <name>图标 17 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/17.png" />
         </contact>
         <contact id= "18" >
                <name>图标 18 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/18.png" />
         </contact>
         <contact id= "19" >
                <name>图标 19 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/19.png" />
         </contact>
         <contact id= "20" >
                <name>图标 20 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/20.png" />
         </contact>
         
         <contact id= "21" >
                <name>图标 21 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/1.png" />
         </contact>
         <contact id= "22" >
                <name>图标 22 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/2.png" />
         </contact>
         <contact id= "23" >
                <name>图标 23 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/3.png" />
         </contact>
         <contact id= "24" >
                <name>图标 24 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/4.png" />
         </contact>
         <contact id= "25" >
                <name>图标 25 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/5.png" />
         </contact>
         <contact id= "26" >
                <name>图标 26 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/6.png" />
         </contact>
         <contact id= "27" >
                <name>图标 27 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/7.png" />
         </contact>
         <contact id= "28" >
                <name>图标 28 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/8.png" />
         </contact>
         <contact id= "29" >
                <name>图标 29 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/9.png" />
         </contact>
         <contact id= "30" >
                <name>图标 30 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/10.png" />
         </contact>
         <contact id= "31" >
                <name>图标 31 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/11.png" />
         </contact>
         <contact id= "32" >
                <name>图标 32 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/12.png" />
         </contact>
 
         <contact id= "33" >
                <name>图标 33 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/13.png" />
         </contact>
         <contact id= "34" >
                <name>图标 34 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/14.png" />
         </contact>
         <contact id= "35" >
                <name>图标 35 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/15.png" />
         </contact>
         <contact id= "36" >
                <name>图标 36 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/16.png" />
         </contact>
         <contact id= "37" >
                <name>图标 37 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/17.png" />
         </contact>
         <contact id= "38" >
                <name>图标 38 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/18.png" />
         </contact>
         <contact id= "39" >
                <name>图标 39 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/19.png" />
         </contact>
         <contact id= "40" >
                <name>图标 40 </name>
                <image src= "http://192.168.34.20:8080/AsyncTaskTest/image/20.png" />
         </contact>
</contacts>

猜你喜欢

转载自lishuaishuai.iteye.com/blog/1806662