Android-PullToRefresh 分页请求网络数据的使用

今天空闲,就下载了chrisbanesAndroid-PullToRefresh,对其Sample进行了简单的修改,完成分页获取网络数据。(数据放于七牛云上了)

上代码


[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. /******************************************************************************* 
  2.  * Copyright 2011, 2012 Chris Banes. 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  * http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  *******************************************************************************/  
  16. package com.handmark.pulltorefresh.samples;  
  17.   
  18. import java.util.ArrayList;  
  19. import java.util.List;  
  20.   
  21. import android.annotation.SuppressLint;  
  22. import android.app.ListActivity;  
  23. import android.os.AsyncTask;  
  24. import android.os.Bundle;  
  25. import android.os.Handler;  
  26. import android.text.format.DateUtils;  
  27. import android.util.Log;  
  28. import android.view.ContextMenu;  
  29. import android.view.ContextMenu.ContextMenuInfo;  
  30. import android.view.Menu;  
  31. import android.view.MenuItem;  
  32. import android.view.View;  
  33. import android.view.ViewGroup;  
  34. import android.widget.AdapterView.AdapterContextMenuInfo;  
  35. import android.widget.BaseAdapter;  
  36. import android.widget.ListView;  
  37. import android.widget.TextView;  
  38. import android.widget.Toast;  
  39.   
  40. import com.handmark.pulltorefresh.library.PullToRefreshBase;  
  41. import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;  
  42. import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;  
  43. import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;  
  44. import com.handmark.pulltorefresh.library.PullToRefreshBase.State;  
  45. import com.handmark.pulltorefresh.library.PullToRefreshListView;  
  46. import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;  
  47. import com.handmark.pulltorefresh.samples.GetNetJsonData.ItemAttri;  
  48.   
  49. /** 
  50.  * ①布局文件中使用PullToRefreshListView,findViewById 
  51.  *  
  52.  * ②设置滑动模式 
  53.  *  
  54.  * ③设置刷新监听事件 
  55.  *  
  56.  * a、getCurrentMode 判断当前刷新的Mode:上拉、下拉 
  57.  *  
  58.  * b、上拉刷新只请求首页数据 toPage = 1、isMore = true 
  59.  *  
  60.  * c、下拉刷新 toPage++,根据isMore来提示显示信息 
  61.  *  
  62.  * ④异步线程请求数据 
  63.  *  
  64.  * a、有返回数据isMore=true; 
  65.  *  
  66.  * b、否则,isMore=false 并通知主线程 
  67.  *  
  68.  * ⑤异步线程完成 执行onRefreshComplete操作 
  69.  *  
  70.  */  
  71.   
  72. @SuppressLint("HandlerLeak")  
  73. public final class PullToRefreshListActivity extends ListActivity {  
  74.     private final String TAG = "PullToRefreshListActivity";  
  75.     /** 首次网络请求页码 */  
  76.     private static final int FIRST_PAGE = 1;  
  77.     /** 数据请求页码 **/  
  78.     private int toPage = 1;  
  79.     /** 更多的网络数据 **/  
  80.     private boolean isMore = true;  
  81.   
  82.     private List<ItemAttri> mListData;// 存储网络数据  
  83.   
  84.     private PullToRefreshListView mPullRefreshListView;  
  85.     private ListViewAdapter mAdapter;// listView的适配器  
  86.   
  87.     @Override  
  88.     public void onCreate(Bundle savedInstanceState) {  
  89.         super.onCreate(savedInstanceState);  
  90.         setContentView(R.layout.activity_ptr_list);  
  91.   
  92.         initView();  
  93.   
  94.         // 初始化监听  
  95.         initEvent();  
  96.   
  97.         // ListView actualListView = mPullRefreshListView.getRefreshableView();  
  98.   
  99.         // Need to use the Actual ListView when registering for Context Menu  
  100.         // registerForContextMenu(actualListView);  
  101.   
  102.         // 获取首页数据并设置listView  
  103.         mListData = new ArrayList<GetNetJsonData.ItemAttri>();  
  104.         new GetDataTask().execute(FIRST_PAGE);  
  105.   
  106.     }  
  107.   
  108.     private void initView() {  
  109.         mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);  
  110.         // 滑动模式设置为双向滑动  
  111.         mPullRefreshListView  
  112.                 .setMode(mPullRefreshListView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START  
  113.                         : Mode.BOTH);  
  114.   
  115.     }  
  116.   
  117.     /** 
  118.      * 初始化监听事件 
  119.      */  
  120.     private void initEvent() {  
  121.         // 设置listView的滑动刷新监听  
  122.         mPullRefreshListView  
  123.                 .setOnRefreshListener(new OnRefreshListener<ListView>() {  
  124.                     @Override  
  125.                     public void onRefresh(  
  126.                             PullToRefreshBase<ListView> refreshView) {  
  127.   
  128.                         // 获取当前时间并格式化  
  129.                         String label = DateUtils.formatDateTime(  
  130.                                 getApplicationContext(),  
  131.                                 System.currentTimeMillis(),  
  132.                                 DateUtils.FORMAT_SHOW_TIME  
  133.                                         | DateUtils.FORMAT_SHOW_DATE  
  134.                                         | DateUtils.FORMAT_ABBREV_ALL);  
  135.   
  136.                         // Update the LastUpdatedLabel  
  137.                         refreshView.getLoadingLayoutProxy()  
  138.                                 .setLastUpdatedLabel(label);  
  139.   
  140.                         if (PullToRefreshBase.Mode.PULL_FROM_START == mPullRefreshListView  
  141.                                 .getCurrentMode()) {// 下拉刷新  
  142.   
  143.                             mPullRefreshListView.getLoadingLayoutProxy()  
  144.                                     .setRefreshingLabel("请稍等...");  
  145.                             mPullRefreshListView.getLoadingLayoutProxy()  
  146.                                     .setPullLabel("下拉刷新...");  
  147.                             mPullRefreshListView.getLoadingLayoutProxy()  
  148.                                     .setReleaseLabel("松开自动刷新");  
  149.   
  150.                             // 重置集合数据  
  151.                             mListData = new ArrayList<ItemAttri>();  
  152.                             new GetDataTask().execute(FIRST_PAGE);  
  153.   
  154.                             // 还原toPage初始值  
  155.                             toPage = 1;  
  156.                             // 还原上拉加载控制变量  
  157.                             isMore = true;  
  158.   
  159.                         } else if (PullToRefreshBase.Mode.PULL_FROM_END == mPullRefreshListView  
  160.                                 .getCurrentMode()) {// 上拉刷新  
  161.   
  162.                             // 上拉刷新时,逐步加载新界面  
  163.                             toPage++;  
  164.   
  165.                             if (isMore) {// 上一次请求有数据  
  166.                                 // 自定义上拉header内容  
  167.   
  168.                                 mPullRefreshListView.getLoadingLayoutProxy()  
  169.                                         .setPullLabel("上拉刷新...");  
  170.                                 mPullRefreshListView.getLoadingLayoutProxy()  
  171.                                         .setRefreshingLabel("正在为你加载更多赛程内容...");  
  172.                                 mPullRefreshListView.getLoadingLayoutProxy()  
  173.                                         .setReleaseLabel("松开自动刷新...");  
  174.                             } else {  
  175.                                 // 上一次请求已经没有数据了  
  176.                                 mPullRefreshListView.getLoadingLayoutProxy()  
  177.                                         .setPullLabel("没有更多了...");  
  178.                                 mPullRefreshListView.getLoadingLayoutProxy()  
  179.                                         .setRefreshingLabel("没有更多了...");  
  180.                                 mPullRefreshListView.getLoadingLayoutProxy()  
  181.                                         .setReleaseLabel("没有更多了...");  
  182.                             }  
  183.                             new GetDataTask().execute(toPage);  
  184.                         }  
  185.   
  186.                     }  
  187.                 });  
  188.   
  189.         // Add an end-of-list listener  
  190.         mPullRefreshListView  
  191.                 .setOnLastItemVisibleListener(new OnLastItemVisibleListener() {  
  192.   
  193.                     @Override  
  194.                     public void onLastItemVisible() {  
  195.                         // listView最后一个item可见时触发  
  196.                         Toast.makeText(PullToRefreshListActivity.this,  
  197.                                 "End of List!", Toast.LENGTH_SHORT).show();  
  198.                     }  
  199.                 });  
  200.   
  201.         /** 
  202.          * Add Sound Event Listener 
  203.          */  
  204.         //SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(  
  205.         //      this);  
  206.         //soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);  
  207.         //soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);  
  208.         //soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);  
  209.         //mPullRefreshListView.setOnPullEventListener(soundListener);  
  210.   
  211.     }  
  212.   
  213.     private class GetDataTask extends AsyncTask<Integer, Void, Void> {  
  214.   
  215.         @Override  
  216.         protected Void doInBackground(Integer... params) {  
  217.             // 本次请求的数据集合  
  218.             List<ItemAttri> currData = new ArrayList<ItemAttri>();  
  219.             currData = new GetNetJsonData().getDataFromJson(params[0]);  
  220.             if (!currData.isEmpty()) {  
  221.                 // 有数据返回  
  222.                 // 数据加入集合中  
  223.                 mListData.addAll(currData);  
  224.             } else {  
  225.                 // 没有数据  
  226.                 isMore = false;  
  227.                 // 向主线程发送通知  
  228.                 mHandler.sendEmptyMessage(0);  
  229.                 // 没有数据toPage--  
  230.                 toPage--;  
  231.             }  
  232.   
  233.             return null;  
  234.         }  
  235.   
  236.         @Override  
  237.         protected void onPostExecute(Void v) {  
  238.   
  239.             if (mAdapter == null) {  
  240.                 mAdapter = new ListViewAdapter();  
  241.   
  242.                 // You can also just use setListAdapter(mAdapter) or  
  243.                 // mPullRefreshListView.setAdapter(mAdapter)  
  244.                 mPullRefreshListView.setAdapter(mAdapter);  
  245.             } else {  
  246.                 mAdapter.notifyDataSetChanged();  
  247.             }  
  248.   
  249.             Log.i(TAG, "page:" + toPage);  
  250.             // Call onRefreshComplete when the list has been refreshed.  
  251.             mPullRefreshListView.onRefreshComplete();// 完成刷新动作  
  252.   
  253.             super.onPostExecute(v);  
  254.         }  
  255.     }  
  256.   
  257.     /** 
  258.      * 接收子线程传递出来的信息 
  259.      */  
  260.     private Handler mHandler = new Handler() {  
  261.         public void handleMessage(android.os.Message msg) {  
  262.             Toast.makeText(PullToRefreshListActivity.this"没有更多了",  
  263.                     Toast.LENGTH_SHORT).show();  
  264.         }  
  265.     };  
  266.   
  267.     private class ListViewAdapter extends BaseAdapter {  
  268.   
  269.         @Override  
  270.         public int getCount() {  
  271.             return mListData.size();  
  272.         }  
  273.   
  274.         @Override  
  275.         public Object getItem(int position) {  
  276.             return mListData.get(position);  
  277.         }  
  278.   
  279.         @Override  
  280.         public long getItemId(int position) {  
  281.             return 0;  
  282.         }  
  283.   
  284.         @Override  
  285.         public View getView(int position, View convertView, ViewGroup parent) {  
  286.             ViewHolder holder = null;  
  287.             if (convertView == null) {  
  288.                 holder = new ViewHolder();  
  289.                 convertView = getLayoutInflater().inflate(  
  290.                         R.layout.item_list_view, null);  
  291.                 holder.tvTitle = (TextView) convertView  
  292.                         .findViewById(R.id.tv_title);  
  293.                 holder.tvTime = (TextView) convertView  
  294.                         .findViewById(R.id.tv_time);  
  295.                 holder.tvContent = (TextView) convertView  
  296.                         .findViewById(R.id.tv_content);  
  297.   
  298.                 convertView.setTag(holder);  
  299.   
  300.             } else {  
  301.                 holder = (ViewHolder) convertView.getTag();  
  302.             }  
  303.   
  304.             holder.tvTitle.setText(mListData.get(position).title);  
  305.             holder.tvTime.setText(mListData.get(position).time);  
  306.             holder.tvContent.setText(mListData.get(position).content);  
  307.   
  308.             return convertView;  
  309.         }  
  310.   
  311.         private class ViewHolder {  
  312.             TextView tvTitle;  
  313.             TextView tvTime;  
  314.             TextView tvContent;  
  315.         }  
  316.   
  317.     }  
  318.       
  319. }  


模拟数据存放在七牛云上

GetNetJsonData.java

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.handmark.pulltorefresh.samples;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.MalformedURLException;  
  8. import java.net.URL;  
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11.   
  12. import org.json.JSONArray;  
  13. import org.json.JSONException;  
  14. import org.json.JSONObject;  
  15.   
  16. import android.util.Log;  
  17.   
  18. /** 
  19.  * 获取模拟数据 
  20.  */  
  21. public class GetNetJsonData {  
  22.   
  23.     /** 
  24.      * 获取网络json数据 
  25.      *  
  26.      * @return 返回数据的list形式 
  27.      * @throws Exception 
  28.      */  
  29.     public List<ItemAttri> getDataFromJson(int pageNum) {  
  30.         List<ItemAttri> dataList = new ArrayList<ItemAttri>();  
  31.         String path = "http://jp-testdata.qiniudn.com/%40%2FlistDataPage"  
  32.                 + pageNum + ".json";  
  33.         URL url;  
  34.         try {  
  35.             url = new URL(path);  
  36.   
  37.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  38.             conn.setReadTimeout(5000);  
  39.             conn.setRequestMethod("GET");  
  40.             if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {  
  41.                 InputStream instream = conn.getInputStream();  
  42.                 dataList = parseJSON(instream);  
  43.             }  
  44.         } catch (MalformedURLException e) {  
  45.             e.printStackTrace();  
  46.         } catch (IOException e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.         for (int i = 0; i < dataList.size(); i++) {  
  50.             Log.i("GetSimulationData""" + dataList.get(i).title);  
  51.         }  
  52.   
  53.         return dataList;  
  54.     }  
  55.   
  56.     /** 
  57.      * 解析JSON 
  58.      */  
  59.     private List<ItemAttri> parseJSON(InputStream instream) {  
  60.   
  61.         List<ItemAttri> lst = new ArrayList<ItemAttri>();  
  62.         byte[] data;  
  63.         try {  
  64.             data = IOUtils.read(instream);  
  65.   
  66.             String jsonStr = new String(data);  
  67.             JSONArray array = new JSONArray(jsonStr);  
  68.             for (int i = 0; i < array.length(); i++) {  
  69.                 JSONObject jsonObj = (JSONObject) array.getJSONObject(i);  
  70.                 ItemAttri v = new ItemAttri(jsonObj.getString("content"),  
  71.                         jsonObj.getString("time"), jsonObj.getString("title"));  
  72.                 lst.add(v);  
  73.             }  
  74.         } catch (IOException e) {  
  75.             e.printStackTrace();  
  76.         } catch (JSONException e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.         return lst;  
  80.     }  
  81.   
  82.     /** 
  83.      * 模拟实体类 
  84.      */  
  85.     public class ItemAttri {  
  86.         public String content;  
  87.         public String time;  
  88.         public String title;  
  89.   
  90.         public ItemAttri(String content, String time, String title) {  
  91.             super();  
  92.             this.content = content;  
  93.             this.time = time;  
  94.             this.title = title;  
  95.         }  
  96.     }  
  97.   
  98. }  
  99.   
  100. class IOUtils {  
  101.     /** 
  102.      * 读取输入流为byte[]数组 
  103.      */  
  104.     static byte[] read(InputStream instream) throws IOException {  
  105.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  106.         byte[] buffer = new byte[1024];  
  107.         int len = 0;  
  108.         while ((len = instream.read(buffer)) != -1) {  
  109.             bos.write(buffer, 0, len);  
  110.         }  
  111.         return bos.toByteArray();  
  112.     }  
  113. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值