Android:仿微博Listview与多线程功能(JSON、数据下载、图片加载、Listview、异步任务)

简介:

解析服务端JSON的内容和图片,通过异步任务下载并设置到listview页上,点击listview跳转到详情页。

1
2
3
4
5
6
7
8
9
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
public  class  WatchingActivity  extends  Activity  implements  OnClickListener, OnItemClickListener
{
     private  ListView mListView;
     private  HashMap<URL, Bitmap> mCacheMap =  new  HashMap<URL, Bitmap>();
     private  View errorView;
     private  View loadingview;
     private  RelativeLayout errorlayout;
     private  Button btn_netRetry;
     private  View headview;
     private  View footview;
     private  View btn_footviewloading;
     private  TextView btn_loadmore;
     private  int  mPage =  1 ;
     private  BaseAdapter mAdapter;
     private  ArrayList<ItemData> mDataList =  new  ArrayList<ItemData>();
     private  View headviewad;
     private  View imageBtn_refresh;
                                                                  
     /*
      * 创建布局
      * 下载内容
      * 解析内容
      * 下载图片
      * 图片缓存
      * 网络错误页面
      * 网络加载页面
      * 增加页眉
      * 加载更多
      * 页眉响应
      * ListView行跳转
      * 内容页显示详情
      */
                                                                  
     /**
      * 1.适配器判断是否为空,生命周期?还是因为是第一次===========> 复用会导致数据重新刷新,不能在原有数据基础上加载
      * 2.页眉整张图片,则无法直接点击------------------->layout拦截掉了监听
      * 3.加载更多链接不在时result会报错空值--------------->
      * 4.mListView.setOnItemClickListener(this);用这个方法监听ListView无效?========>监听行布局对象
      * 5.顶部刷新按钮为何不响应?
      * 6.行布局的进度条为何找不到?========>已解决
      * 7.include移位就报错==============>没问题
      * 8.控件层次如何改变=============> relative根据xml代码位置
      * 9.setonItemClick  position要减1才能对应?============> 加完headview后,position初始值自动加1
      *
      */
                                                                  
     class  ItemData
     {
         String imageUrl;
         String title;
         String from;
         String time;
         String content;
         public  ItemData(String imageUrl, String title, String from,
                 String time, String content)
         {
             super ();
             this .imageUrl = imageUrl;
             this .title = title;
             this .from = from;
             this .time = time;
             this .content = content;
         }
                                                                       
     }
                                                                  
     class  ViewHolder
     {
         ImageView imageView;
         TextView textView_title;
         TextView textView_from;
         TextView textView_time;
                                                                      
         ProgressBar progressBar_imageLoading;
     }
                                                                  
     @Override
     protected  void  onCreate(Bundle savedInstanceState)
     {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_watching);
                                                                      
         setUI();
                                                                      
     }
     private  void  setUI()
     {
         LayoutInflater inflater = getLayoutInflater();
         headview = inflater.inflate(R.layout.headview,  null );
         footview = inflater.inflate(R.layout.footview,  null );
         btn_footviewloading = footview.findViewById(R.id.footview_loading);
         btn_loadmore = (TextView) footview.findViewById(R.id.btn_loadmore);
         headviewad = headview.findViewById(R.id.imageView_headview_ad);
         imageBtn_refresh = findViewById(R.id.imageBtn_refresh);
                                                                      
         btn_netRetry = (Button) findViewById(R.id.btn_netRetry);
         loadingview = findViewById(R.id.loadingview);
         errorView = findViewById(R.id.errorview);
         mListView = (ListView) findViewById(R.id.listView_watching);
         mListView.addHeaderView(headview); //注意:一定要在setAdapter之前调用,所以一般在找到listview之后就添加
         mListView.addFooterView(footview);
                                                                      
         loadTask();
                                                                      
         //网络连接重试按钮
         btn_netRetry.setOnClickListener( this );
         //分页加载更多
         btn_loadmore.setOnClickListener( this );
         //点击ListView页眉广告
         headviewad.setOnClickListener( this );
         //点击顶部刷新页面
         btn_netRetry.setOnClickListener( this );
         //点击listview跳转
         mListView.setOnItemClickListener( this );
     }
                                                                  
     //按钮点击事件
     @Override
     public  void  onClick(View v)
     {
         switch  (v.getId())
         {
             case  R.id.btn_netRetry:
                 errorView.setVisibility(View.GONE);
                 mPage =  1 ;
                 loadTask();
                 break ;
                                                                              
             case  R.id.btn_loadmore:
                 btn_loadmore.setVisibility(View.INVISIBLE);
                 btn_footviewloading.setVisibility(View.VISIBLE);
                 loadTask();
                 break ;
                                                                              
             case  R.id.imageView_headview_ad:
                 Toast.makeText(WatchingActivity. this , Contant.HEADVIEW_TOAST, Toast.LENGTH_LONG).show();
                 break ;
                                                                              
             case  R.id.imageBtn_refresh:
                 loadTask();
                 break ;
                                                                              
             default :
                 break ;
         }
     }
                                                                  
     //监听listview
     @Override
     public  void  onItemClick(AdapterView<?> parent, View view,  int  position,
             long  id)
     {
         if (view.getId() == R.id.watching_item) //监听的对象是行布局
         {
             Intent intent =  new  Intent(WatchingActivity. this , ContentActivity. class );
             ItemData data = mDataList.get(position -  1 );
             String fromtime = data.from + " "  + Contant.TIME_YEAR + data.time;
             intent.putExtra(Contant.KEY_INTENTER_TITLE, data.title);
             intent.putExtra(Contant.KEY_INTENTER_FROMTIME, fromtime);
             intent.putExtra(Contant.KEY_INTENTER_CONTENT, data.content);
             startActivity(intent);
         }
     }
                                                                  
     //启动异步任务
     private  void  loadTask()
     {
         URL dataUrl =  null ;
         try
         {
             dataUrl =  new  URL(Contant.URL_DATA + mPage + Contant.URL_DATA_FILEFORM);
             // 异步任务下载数据
             LoadDataTask loadDataTask =  new  LoadDataTask();
             loadDataTask.execute(dataUrl);
         }
         catch  (MalformedURLException e)
         {
             e.printStackTrace();
         }
     }
                                                                  
     // 异步任务下载数据
     class  LoadDataTask  extends  AsyncTask<URL, Void, String>
     {
         @Override
         protected  void  onPreExecute()
         {
             loadingview.setVisibility(View.VISIBLE);
         }
         @Override
         protected  String doInURL...  params)
         {
             InputStream is =  null ;
             ByteArrayBuffer strBuf =  new  ByteArrayBuffer( 59658 ); //使用ByteArrayBuffer,直接使用String可能造成读取到的部分内容乱码
             try
             {
                 HttpURLConnection conn = (HttpURLConnection) params[ 0 ].openConnection();
                 conn.setConnectTimeout(Contant.HTTP_TIME_OUT);
                 conn.setReadTimeout(Contant.HTTP_TIME_OUT);
                 // 判断网络连接是否正常
                 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
                 {
                     //返回错误提示页面
                     return  null ;
                 }
                                                                              
                 // 下载数据
                 is = conn.getInputStream();
                 byte [] buf =  new  byte [ 1024 ];
                 int  len =  0 ;
                                                                              
                 while  (- 1  != (len = is.read(buf)))
                 {
                     strBuf.append(buf,  0 , len); //直接加入ByteArrayBuffer
                 }
             }
             catch  (IOException e)
             {
                 e.printStackTrace();
             }
             finally
             {
                 if  (is !=  null )
                 {
                     try
                     {
                         is.close();
                     }
                     catch  (IOException e)
                     {
                         e.printStackTrace();
                     }
                 }
             }
             return  new  String(strBuf.buffer()); //bytebuffer数组转成字符串
         }
                                                                      
         // 下载数据解析,更新控件内容
         @Override
         protected  void  onPostExecute(String result)
         {
             loadingview.setVisibility(View.GONE);
                                                                          
             //判断result是否为空
             if (TextUtils.isEmpty(result.trim()))
             {
                 btn_loadmore.setVisibility(View.GONE);
                 errorView.setVisibility(View.VISIBLE);
                 mListView.setVisibility(View.GONE);
                // return;
             }
             else
             {
                 btn_loadmore.setVisibility(View.VISIBLE);
                 btn_footviewloading.setVisibility(View.INVISIBLE);
                 mListView.setVisibility(View.VISIBLE);
                 // 解析json数据
                 ArrayList<ItemData> dataList = parse(result);
                 //更新控件内容
                 setListData(dataList);
                                                                              
             }
         }
     }
                                                                  
    //更新行内容
     private  void  setListData(ArrayList<ItemData> dataList)
     {
         //判断mAdapter是否为空,复用mAdapter实现内容加载,重新set会导致所有内容重新加载(跳到第一行)
         if ( null  == mAdapter)
         {
             createAdapter(dataList); //创建适配器
             mListView.setAdapter(mAdapter);
         }
         else
         {
             mAdapter.notifyDataSetChanged(); //通知listview更新界面
         }
     }
                                                                  
     // 解析json数据
     private  ArrayList<ItemData> parse(String result)
     {
         try
         {
             JSONArray jsonArray =  new  JSONArray(result);
             mPage++; //数据解析完成后,页数修改
             for  ( int  i =  0 ; i < jsonArray.length(); i++)
             {
                 JSONObject jsonObject = jsonArray.getJSONObject(i);
                 String imageUrl = Contant.URL_HOST + jsonObject.getString(Contant.KEY_JSON_IMGURL);
                 String title = jsonObject.getString(Contant.KEY_JSON_TITLE);
                 String from = jsonObject.getString(Contant.KEY_JSON_FROM);
                 String time = jsonObject.getString(Contant.KEY_JSON_TIME);
                 String content = jsonObject.getString(Contant.KEY_JSON_CONTENT);
                 ItemData itemData =  new  ItemData(imageUrl, title, from, time,content);
                 mDataList.add(itemData);
             }
         }
         catch  (JSONException e)
         {
             e.printStackTrace();
         }
         return  mDataList;
     }
                                                                  
     //创建Adapter,设置LiseView
     private  void  createAdapter( final  ArrayList<ItemData> dataList)
     {
         mAdapter =  new  BaseAdapter()
         {
             @Override
             public  View getView( int  position, View convertView,ViewGroup parent)
             {
                 ViewHolder holder;
                 if (convertView ==  null )
                 {
                     LayoutInflater inflater = getLayoutInflater();
                     convertView = inflater.inflate(R.layout.watch_layout,  null );
                     holder =  new  ViewHolder();
                     holder.imageView = (ImageView) convertView.findViewById(R.id.imgView_watch_newspic);
                     holder.textView_title = (TextView) convertView.findViewById(R.id.txtView_watch_title);
                     holder.textView_from = (TextView) convertView.findViewById(R.id.txtView_from);
                     holder.textView_time = (TextView) convertView.findViewById(R.id.txtView_time);
                     holder.progressBar_imageLoading = (ProgressBar) convertView.findViewById(R.id.progressBar_imageloading);
                     convertView.setTag(holder);
                 }
                 else
                 {
                     holder = (ViewHolder) convertView.getTag();
                 }
                                                                              
                 ItemData itemData = dataList.get(position);
                                                                              
                 //启动图片下载任务
                 try
                 {
                     URL url =  new  URL(itemData.imageUrl);
                     if (mCacheMap.containsKey(url))
                     {
                         holder.imageView.setImageBitmap(mCacheMap.get(url));
                     }
                     else
                     {
                         LoadImageTask imageTask =  new  LoadImageTask(holder.imageView,holder.progressBar_imageLoading);
                         imageTask.execute(url);
                     }
                 }
                 catch  (MalformedURLException e)
                 {
                     e.printStackTrace();
                 }
                                                                              
                 holder.textView_title.setText(itemData.title);
                 holder.textView_from.setText(itemData.from);
                 holder.textView_time.setText(itemData.time);
                 return  convertView;
             }
                                                                          
             @Override
             public  long  getItemId( int  position)
             {
                 return  0 ;
             }
                                                                          
             @Override
             public  Object getItem( int  position)
             {
                 return  null ;
             }
                                                                          
             @Override
             public  int  getCount()
             {
                 return  dataList.size();
             }
         };
     }
                                                                  
     //下载图片
     class  LoadImageTask  extends  AsyncTask<URL, Void, Bitmap>
     {
         private  ImageView imageView;
         ProgressBar progressBar_imageLoading;
         public  LoadImageTask(ImageView imageView, ProgressBar progressBar_imageLoading)
         {
             this .imageView = imageView;
             this .progressBar_imageLoading = progressBar_imageLoading;
         }
                                                                      
         @Override
         protected  void  onPreExecute()
         {
             progressBar_imageLoading.setVisibility(View.VISIBLE);
         }
                                                                      
         //下载图片
         @Override
         protected  Bitmap doInURL...  params)
         {
             InputStream is =  null ;
             Bitmap bitmap =  null ;
             try
             {
                 //判断网络连接
                 HttpURLConnection conn = (HttpURLConnection) params[ 0 ].openConnection();
                 conn.setConnectTimeout(Contant.HTTP_TIME_OUT);
                 conn.setReadTimeout(Contant.HTTP_TIME_OUT);
                 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
                 {
                     return  null ;
                 }
                                                                              
                 //由url获取bitmap对象
                 is = conn.getInputStream();   //简写方法:is = params[0].openStream()
                 bitmap = BitmapFactory.decodeStream(is);
                 mCacheMap.put(params[ 0 ], bitmap);
             }
             catch  (IOException e)
             {
                 e.printStackTrace();
             }
             finally
             {
                 if ( null  != is )
                 {
                     try
                     {
                         is.close();
                     }
                     catch  (IOException e)
                     {
                         e.printStackTrace();
                     }
                 }
             }
             return  bitmap;
         }
                                                                      
         @Override
         protected  void  onPostExecute(Bitmap bitmap)
         {
             if (bitmap ==  null )
             {
                 //图片加载失败
             }
             else
             {
                 progressBar_imageLoading.setVisibility(View.INVISIBLE);
                 imageView.setImageBitmap(bitmap);
             }
         }
     }
                                                                  
     @Override
     public  boolean  onCreateOptionsMenu(Menu menu)
     {
         getMenuInflater().inflate(R.menu.watching, menu);
         return  true ;
     }
}




其他优化和扩展:

1.图片加载 与设置图片方法一样,将控件对象传到异步任务里

2.惰性加载


其他相关:

1.隐藏headview

1
2
3
4
5
6
7
8
9
<LinearLayout android:id= "@+id/item_root"
     android:layout_width= "fill_parent"
     android:layout_height= "50dip"
     android:orientation= "vertical"  >
  <LinearLayout android:id= "@+id/item_container"
<TextView  android:id= "@+id/tv_1"  />
<TextView  android:id= "@+id/tv_2"  />
  </LinearLayout>
</LinearLayout >

要隐藏的view必须不能是根目录的view的id。







本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1215407,如需转载请自行联系原作者
目录
相关文章
|
23天前
|
JSON JavaScript 数据格式
jwt-auth插件实现了基于JWT(JSON Web Tokens)进行认证鉴权的功能。
jwt-auth插件实现了基于JWT(JSON Web Tokens)进行认证鉴权的功能。
38 1
|
1月前
|
Java 调度 Android开发
构建高效Android应用:探究Kotlin多线程编程
【2月更文挑战第17天】 在现代移动开发领域,性能优化一直是开发者关注的焦点。特别是在Android平台上,合理利用多线程技术可以显著提升应用程序的响应性和用户体验。本文将深入探讨使用Kotlin进行Android多线程编程的策略与实践,旨在为开发者提供系统化的解决方案和性能提升技巧。我们将从基础概念入手,逐步介绍高级特性,并通过实际案例分析如何有效利用Kotlin协程、线程池以及异步任务处理机制来构建一个更加高效的Android应用。
40 4
|
1月前
|
XML 缓存 Android开发
Android开发,使用kotlin学习多媒体功能(详细)
Android开发,使用kotlin学习多媒体功能(详细)
98 0
|
1月前
|
API 数据库 Android开发
构建高效Android应用:探究Kotlin多线程优化策略
【2月更文挑战第14天】随着移动设备性能的日益强大,用户对应用程序的响应速度和流畅性要求越来越高。在Android开发中,合理利用多线程技术是提升应用性能的关键手段之一。Kotlin作为一种现代的编程语言,其协程特性为开发者提供了更为简洁高效的多线程处理方式。本文将深入探讨使用Kotlin进行Android多线程编程的最佳实践,包括协程的基本概念、优势以及在实际项目中的应用场景和性能优化技巧,旨在帮助开发者构建更加高效稳定的Android应用。
|
1月前
|
数据采集 存储 Java
「多线程大杀器」Python并发编程利器:ThreadPoolExecutor,让你一次性轻松开启多个线程,秒杀大量任务!
「多线程大杀器」Python并发编程利器:ThreadPoolExecutor,让你一次性轻松开启多个线程,秒杀大量任务!
|
24天前
|
存储 算法 Java
【C/C++ 线程池设计思路】 深入探索线程池设计:任务历史记录的高效管理策略
【C/C++ 线程池设计思路】 深入探索线程池设计:任务历史记录的高效管理策略
70 0
|
4天前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android&#39;s AsyncTask simplifies asynchronous tasks for brief background work, bridging UI and worker threads. It involves execute() for starting tasks, doInBackground() for background execution, publishProgress() for progress updates, and onPostExecute() for returning results to the main thread.
5 0
|
4天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
5 0
|
7天前
|
Java API 调度
安卓多线程和并发处理:提高应用效率
【4月更文挑战第13天】本文探讨了安卓应用中多线程和并发处理的优化方法,包括使用Thread、AsyncTask、Loader、IntentService、JobScheduler、WorkManager以及线程池。此外,还介绍了RxJava和Kotlin协程作为异步编程工具。理解并恰当运用这些技术能提升应用效率,避免UI卡顿,确保良好用户体验。随着安卓技术发展,更高级的异步处理工具将助力开发者构建高性能应用。
|
14天前
|
Java Spring
定时任务里面的任务多线程操作
该内容是关于Spring Boot中配置异步任务和定时任务的代码示例。首先通过`@Configuration`和`@EnableAsync`开启异步支持,然后定义线程池,如使用`ThreadPoolExecutor`并设置核心线程数、最大线程数等参数。接着,在需要异步执行的方法上添加`@Async`注解。此外,通过`@EnableScheduling`开启定时任务,并使用`@Scheduled`定义具体任务和执行周期。若需指定多个线程池,可以创建不同的`Executor` bean,并在`@Async`中指定线程池名称。
19 2

热门文章

最新文章