• 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 = 0;   //最后的可视项索引   
        
        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", 1);
            params.put("limit", 10);
            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 = 0; 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 + 1){
                    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 + 1);
            params.put("limit", 10);
            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() -1){
                    //mLoadBtn.setText("正在加载中...");
                    MyRunnable r = new MyRunnable();
                    handler.postDelayed(r, 2000);
                }
            }
            
        }
    
        @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, 3000);
            HttpConnectionParams.setConnectionTimeout(params, 3000);
            HttpConnectionParams.setSoTimeout(params, 3000);
            
            // 设置我们的HttpClient支持HTTP和HTTPS两种模式
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            
            // 使用线程安全的连接管理来创建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) - 1) * 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 = 0;
            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地址下载

  • 相关阅读:
    分布式事务的MQ实现
    zipkin 介绍入门
    线程5问?
    微服务分布式系统架构,转载,备份
    微服务,分布式架构
    史上最全 40 道 Dubbo 面试题及答案,看完碾压面试官!
    Tomcat优化
    windows 下安装kafka
    经典台词
    分布式锁3种实现
  • 原文地址:https://www.cnblogs.com/tplovejava/p/3956534.html
Copyright © 2020-2023  润新知