这次在一的基础上做了数据通过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下拉加载二(分页)的更多相关文章

  1. ListView下拉加载一(分页)

    首先创建在主xml里放置一个listview列表,代码如下: <LinearLayout xmlns:android="http://schemas.android.com/apk/r ...

  2. Flutter 开发从 0 到 1(四)ListView 下拉加载和加载更多

    在<APP 开发从 0 到 1(三)布局与 ListView>我们完成了 ListView,这篇文章将做 ListView 下拉加载和加载更多. ListView 下拉加载 Flutter ...

  3. WP & Win10开发:实现ListView下拉加载的两种方法

    1.通过ListView控件的ContainerContentChanging方法.该方法在列表项被实例化时触发,在列表项最后一个项目实例化的时候触发刷新数据逻辑就可以实现下拉加载了. 代码如下:// ...

  4. Windows Phone 8.1开发:如何让ListView下拉加载更多?

    Windows Phone 8.1开发中使用ListView作为数据呈现载体时,经常需要一个下拉(拇指向上滑动)加载更多的交互操作.如何完成这一操作呢?下面为您阐述. 思路是这样的: 1.在ListV ...

  5. android UI进阶之实现listview的下拉加载

    关于listview的操作五花八门,有下拉刷新,分级显示,分页列表,逐页加载等,以后会陆续和大家分享这些技术,今天讲下下拉加载这个功能的实现. 最初的下拉加载应该是ios上的效果,现在很多应用如新浪微 ...

  6. 微信小程序中如何实现分页下拉加载?(附源码)

    转眼间坚持写教你微信小程序系列已经有十节系列课程了,每天的工作压力繁重,小女子也不知道自己还能坚持这样的系列教程多久.只希望每篇教程真的对大家有帮助.这节课我们要介绍的就是如何实现分页的下拉加载,我们 ...

  7. Flutter学习笔记(25)--ListView实现上拉刷新下拉加载

    如需转载,请注明出处:Flutter学习笔记(25)--ListView实现上拉刷新下拉加载 前面我们有写过ListView的使用:Flutter学习笔记(12)--列表组件,当列表的数据非常多时,需 ...

  8. 集成iscroll 下拉加载更多 jquery插件

    一个插件总是经过了数月的沉淀,不断的改进而成的.最初只是为了做个向下滚动,自动加载的插件.随着需求和功能的改进,才有了今天的这个稍算完整的插件. 一.插件主功能: 1.下拉加载 2.页面滚动到底部自动 ...

  9. ASP.NET仿新浪微博下拉加载更多数据瀑布流效果

    闲来无事,琢磨着写点东西.貌似页面下拉加载数据,瀑布流的效果很火,各个网站都能见到各式各样的展示效果,原理大同小异.于是乎,决定自己写一写这个效果,希望能给比我还菜的菜鸟们一点参考价值. 在开始之前, ...

随机推荐

  1. android selector 开始自定义样式

    Selector的结构描述: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:a ...

  2. PeopleSoft Home Subdirectories

    PeopleSoft Home Subdirectories appserv — home to the Application Server and Process Scheduler Server ...

  3. 搭建S3C6410开发板的测试环境

      因为ARM架构的开发板可基于X86架构的PC在CPU指令以及二进制上都有所不同,而且如果linux驱动需要访问硬件,这些硬件很难在PC上模拟,所以就需要我们在带有这些硬件的开发板上进行调试和测试. ...

  4. java关键字 super 和 this

    简单粗暴的说就是: super: 是指父类,想要在子类方法中调用父类的实例变量或方法可以通过super 来访问 this:是指当前类,想要访问当前类的实例变量和方法可以使用this,同时可以省略

  5. 异步记载数据时page是怎么计算的

    最近一直在完善基于Busybox做的ARM Linux的根文件系统,由于busybox是一个精简的指令集组成的简单文件系统,其优点就是极精简,满足了Linux基本的启动需求,由于它几乎没有什么后台服务 ...

  6. 一个可拖拽的DIV框框

    http://codepen.io/lrelia/pen/bEyLB 使用了JQuery UI库, draggable来自于JQuery UI库

  7. AjaxUpload跨域上传问题

    1. 调用上传的html页面所在域名是 www.abc.com ,添加document.domain <script> document.domain = "abc.com&qu ...

  8. 大理石在哪里UVa 10474

    我自己写的代码 #include<iostream>#include<algorithm>using namespace std;int main(){    int N,a[ ...

  9. linux下打开、关闭tomcat,实时查看tomcat运行日志

    启动:一般是执行sh tomcat/bin/startup.sh 停止:一般是执行sh tomcat/bin/shutdown.sh脚本命令 查看:执行ps -ef |grep tomcat 输出如下 ...

  10. noi 6047 分蛋糕

    题目链接:http://noi.openjudge.cn/ch0405/6047/ 和Uva1629很类似,不过,可能用记忆化难写一点,状态初始化懒得搞了.就用循环好了. 状态描叙也可以修改,那个题目 ...