ListView下拉加载二(分页)
这次在一的基础上做了数据通过HttpClient远程获取显示 并且分页,首先看下效果吧:
以上就是效果图了 下面看下具体代码实现吧
主要代码和上节差不多
主入口代码:
package com.tp.soft.app; import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast; import com.tp.soft.entity.Article;
import com.tp.soft.http.HttpUtil;
import com.tp.soft.io.IOUtil;
import com.tp.soft.util.Constant; public class MainActivity extends Activity implements OnScrollListener, OnItemClickListener{ private ListView mListView; private View mLoadMoreView; private ProgressBar mLoadBtn; private PageAdapter adapter; private Handler handler = new Handler(); private int curPage; private int visibleItemCount; // 当前窗口可见项总数 private int visibleLastIndex = ; //最后的可视项索引 private long total;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mLoadMoreView = getLayoutInflater().inflate(R.layout.loadmore, null);
mLoadBtn = (ProgressBar) mLoadMoreView.findViewById(R.id.progressBar1);
//mLoadBtn.setOnClickListener(this); mListView = (ListView) findViewById(R.id.menuList); mListView.addFooterView(mLoadMoreView);
Map<String, Object> params = new HashMap<String, Object>();
params.put("curPage", );
params.put("limit", );
List<Article> articleList = getArticleList(params);
adapter = new PageAdapter(articleList);
mListView.setAdapter(adapter); //下拉滚动触发事件
mListView.setOnScrollListener(this);
mListView.setOnItemClickListener(this);
} private List<Article> getArticleList(Map<String, Object> params) {
HttpResponse response = HttpUtil.getHttpResponse(Constant.FINDARTICLE, params, Constant.ENCODING);
List<Article> articles = new ArrayList<Article>();
if(response!=null){
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
try{
IOUtil ioUtil = new IOUtil();
String resultJson = ioUtil.getJson(response.getEntity().getContent());
JSONObject jsonObject = new JSONObject(resultJson);
curPage = jsonObject.getInt("curPage");
total = jsonObject.getLong("total");
JSONArray jsonArray = jsonObject.getJSONArray("rows");
for (int i = ; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
int id = obj.getInt("a_id");
String title = obj.getString("title");
String content = obj.getString("content");
Timestamp creat_time = new Timestamp(obj.getLong("create_time"));
Article article = new Article();
article.setA_id(id);
article.setTitle(title);
article.setContent(content);
article.setCreate_time(creat_time);
articles.add(article);
}
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return articles;
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
} /*@Override
public void onClick(View v) {
mLoadBtn.setText("正在加载中...");
MyRunnable r = new MyRunnable();
handler.postDelayed(r, 2000);
}*/ class MyRunnable implements Runnable{
@Override
public void run() {
Log.e("visibleLastIndex", visibleLastIndex+"");
if(visibleLastIndex== total + ){
mListView.removeFooterView(mLoadMoreView);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "数据全部加载完成", Toast.LENGTH_SHORT).show();
}else{
loadMoreDate();
} //更新UI
adapter.notifyDataSetChanged();
//mLoadBtn.setText("查看更多...");
}
} class PageAdapter extends BaseAdapter { List<Article> itemList; public PageAdapter(List<Article> itemList){
this.itemList = itemList;
} @Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.menu, null);
}
TextView titleView = (TextView) convertView.findViewById(R.id.showView);
TextView contentView = (TextView) convertView.findViewById(R.id.content);
titleView.setText(itemList.get(position).getTitle());
contentView.setText(itemList.get(position).getContent()); return convertView;
} @Override
public long getItemId(int position) {
return position;
} @Override
public Object getItem(int position) {
return itemList.get(position);
} @Override
public int getCount() {
return itemList.size();
} public void addItem(Article article){
itemList.add(article);
}
} private void loadMoreDate() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("curPage", curPage + );
params.put("limit", );
List<Article> articleList = getArticleList(params);
for (Article article : articleList) {
adapter.addItem(article);
}
} @Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
visibleLastIndex = totalItemCount;
} @Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//不滚动
if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){
//滚动最底部
if(view.getLastVisiblePosition() == view.getCount() -){
//mLoadBtn.setText("正在加载中...");
MyRunnable r = new MyRunnable();
handler.postDelayed(r, );
}
} } @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
ListView listView = (ListView) parent;
Article article = (Article) listView.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, ArticleDetalActivity.class);
intent.putExtra("article", article);
startActivity(intent);
} }
文章详细信息显示ArticleDetalActivity代码:
package com.tp.soft.app; import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView; import com.tp.soft.entity.Article;
import com.tp.soft.util.DateUtil; public class ArticleDetalActivity extends Activity implements OnClickListener{ private Handler handler = new Handler(); private TextView mTitle;
private TextView mContent;
private TextView mTime; private ImageButton mBackBtn; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article_detal); mTitle = (TextView) findViewById(R.id.d_title);
mContent = (TextView) findViewById(R.id.d_content);
mTime = (TextView) findViewById(R.id.d_time); mBackBtn = (ImageButton) findViewById(R.id.backBtn); Intent intent = getIntent();
Article article = (Article) intent.getSerializableExtra("article");
mTitle.setText(article.getTitle());
mContent.setText(article.getContent());
mTime.setText("发表日期:"+DateUtil.timestampToStr(article.getCreate_time(), "yyyy-MM-dd HH:mm:ss")); mBackBtn.setOnClickListener(this);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.article_detal, menu);
return true;
} @Override
public void onClick(View v) {
ArticleDetalActivity.this.setResult(RESULT_OK, getIntent());
ArticleDetalActivity.this.finish();
}
}
HttpUtil封装:
package com.tp.soft.http; import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import android.util.Log; public class HttpUtil {
public static HttpResponse getHttpResponse(String serverPath, Map<String, Object> params, String encoding){
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
if(null != params && !params.isEmpty()){
for(Map.Entry<String, Object> entry : params.entrySet()){
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
} HttpResponse response = null;
try {
HttpPost post = new HttpPost(serverPath);
post.setEntity(new UrlEncodedFormEntity(pairs, encoding));
response = getHttpClient().execute(post);
}catch (ConnectTimeoutException e) {
Log.e("提示", "连接超时");
return null;
} catch (SocketTimeoutException e) {
Log.e("提示", "Socket连接超时");
return null;
} catch (Exception e) {
Log.e("提示", e.getLocalizedMessage());
return null;
}
return response;
} public static synchronized HttpClient getHttpClient(){
HttpParams params = new BasicHttpParams();
ConnManagerParams.setTimeout(params, );
HttpConnectionParams.setConnectionTimeout(params, );
HttpConnectionParams.setSoTimeout(params, ); // 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), ));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), )); // 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
HttpClient client = new DefaultHttpClient(conMgr ,params);
return client;
}
}
服务器代码:
@POST
@Path(value="/findArticle")
@Produces(MediaType.APPLICATION_JSON)
@Override
public Result findArticleAll(@FormParam(value="curPage") String curPage, @FormParam(value="limit") String limit)throws BaseServiceException {
Result result = new Result();
List<Article> aList = new ArrayList<Article>();
Article article = new Article();
article.setPageable(true);
article.setStart((Integer.parseInt(curPage) - ) * Integer.parseInt(limit));
article.setLimit(Integer.parseInt(limit));
try{
aList = articleDao.find(article);
}catch (DataAccessException e) {
LOG.error("【ibatis】查询文章列表失败", e);
throw new BaseServiceException(e.getLocalizedMessage());
} long total = ;
try{
total = articleDao.getTotal(article);
}catch (DataAccessException e) {
LOG.error("【ibatis】查询文章总数失败", e);
throw new BaseServiceException(e.getLocalizedMessage());
}
result.setRows(aList);
result.setCurPage(Integer.parseInt(curPage));
result.setTotal(total);
return result;
}
核心代码就这么多了 界面代码就不一一贴出了
想要具体代码可以到http://download.csdn.net/detail/taopeng_100/7864393地址下载
ListView下拉加载二(分页)的更多相关文章
- ListView下拉加载一(分页)
首先创建在主xml里放置一个listview列表,代码如下: <LinearLayout xmlns:android="http://schemas.android.com/apk/r ...
- Flutter 开发从 0 到 1(四)ListView 下拉加载和加载更多
在<APP 开发从 0 到 1(三)布局与 ListView>我们完成了 ListView,这篇文章将做 ListView 下拉加载和加载更多. ListView 下拉加载 Flutter ...
- WP & Win10开发:实现ListView下拉加载的两种方法
1.通过ListView控件的ContainerContentChanging方法.该方法在列表项被实例化时触发,在列表项最后一个项目实例化的时候触发刷新数据逻辑就可以实现下拉加载了. 代码如下:// ...
- Windows Phone 8.1开发:如何让ListView下拉加载更多?
Windows Phone 8.1开发中使用ListView作为数据呈现载体时,经常需要一个下拉(拇指向上滑动)加载更多的交互操作.如何完成这一操作呢?下面为您阐述. 思路是这样的: 1.在ListV ...
- android UI进阶之实现listview的下拉加载
关于listview的操作五花八门,有下拉刷新,分级显示,分页列表,逐页加载等,以后会陆续和大家分享这些技术,今天讲下下拉加载这个功能的实现. 最初的下拉加载应该是ios上的效果,现在很多应用如新浪微 ...
- 微信小程序中如何实现分页下拉加载?(附源码)
转眼间坚持写教你微信小程序系列已经有十节系列课程了,每天的工作压力繁重,小女子也不知道自己还能坚持这样的系列教程多久.只希望每篇教程真的对大家有帮助.这节课我们要介绍的就是如何实现分页的下拉加载,我们 ...
- Flutter学习笔记(25)--ListView实现上拉刷新下拉加载
如需转载,请注明出处:Flutter学习笔记(25)--ListView实现上拉刷新下拉加载 前面我们有写过ListView的使用:Flutter学习笔记(12)--列表组件,当列表的数据非常多时,需 ...
- 集成iscroll 下拉加载更多 jquery插件
一个插件总是经过了数月的沉淀,不断的改进而成的.最初只是为了做个向下滚动,自动加载的插件.随着需求和功能的改进,才有了今天的这个稍算完整的插件. 一.插件主功能: 1.下拉加载 2.页面滚动到底部自动 ...
- ASP.NET仿新浪微博下拉加载更多数据瀑布流效果
闲来无事,琢磨着写点东西.貌似页面下拉加载数据,瀑布流的效果很火,各个网站都能见到各式各样的展示效果,原理大同小异.于是乎,决定自己写一写这个效果,希望能给比我还菜的菜鸟们一点参考价值. 在开始之前, ...
随机推荐
- CSS深入理解之overflow
CSS深入理解之overflow 前言 这是跟着张鑫旭重学CSS的overflow篇 基本属性 overflow有以下五个基本属性: 1.visible : 默认值,具体表现为,应用此属性后,子元素超 ...
- aix磁盘分区挂载问题
aix在进行磁盘分区挂载时,可能会报错
- Android Studio Jni 环境搭建
第一步:NDK环境搭建,点击下图红色框区域查看NDK下载和环境配置 安照正常情况是很慢的或者无法下载成功的,这个时候可以去下载NDK压缩包进行解压.下面给出两个下载地址 (1)官网:http://we ...
- java 日期转时间戳,时间戳转为日期
package date; import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Dat ...
- mac下使用gcc
1.下载安装macports:http://www.macports.org/install.php 安装完成之后,打开终端 2.在终端中输入 port install gcc_select 3.使用 ...
- STL—Vector简介
有关C++ STL 中的vector向量的用法(代码示例) 一. 简介 Vector是一个称为向量的顺序容器(不明白顺序容器与关联容器的可以Google). 二. 特点 1. 动态(相当于一个动态数组 ...
- 在执行Java命令或eclipse启动程序,提示报错’jvm.cfg无法找到’的解决办法
一.问题背景 昨天debug代码的时候,突然发现无法启动程序了.每次启动程序的时候均报如下错误:(回家以后重现了下这个问题.发现不同电脑,所在的lib下的文件夹不一样,应该和jdk安装时硬件的情况有关 ...
- css深入理解z-index
z-index取值 z-index:auto;z-index:<integer>;z-index:inherit;继承 特性: 1.支持负值2.支持css3 animation动画;3.在 ...
- Coursera台大机器学习课程笔记6 -- The VC Dimension
本章的思路在于揭示VC Dimension的意义,简单来说就是假设的自由度,或者假设包含的feature vector的个数(一般情况下),同时进一步说明了Dvc和,Eout,Ein以及Model C ...
- Python练习,网络小爬虫(初级)
最近还在看Python版的rcnn代码,附带练习Python编程写一个小的网络爬虫程序. 抓取网页的过程其实和读者平时使用IE浏览器浏览网页的道理是一样的.比如说你在浏览器的地址栏中输入 www ...