android ListView 分页加载数据

1.mainActivity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context="mydemo.mycom.demo2.Home">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_home_to_login"
            android:text="@string/btn_to_register"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_exit"
            android:text="@string/btn_to_exit"/>
        </LinearLayout>

   <ListView
       android:id="@+id/lv"
       android:layout_width="fill_parent"
       android:layout_height="match_parent"></ListView>

</LinearLayout>

2.ListView的itemActivity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="horizontal"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context="mydemo.mycom.demo2.Home">

        <TextView
            android:id="@+id/tv_id"
            android:layout_width="wrap_content"
            android:textColor="#FF172366"
            android:padding="5dp"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/tv_username"
            android:layout_width="wrap_content"
            android:padding="5dp"
            android:textColor="#FF870918"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tv_password"
            android:layout_width="wrap_content"
            android:padding="5dp"
            android:layout_height="wrap_content" />


</LinearLayout>

3.ListView footerActivity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="mydemo.mycom.demo2.Footer">

    <ProgressBar
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyle"
        />
    <TextView android:text="@string/load_text"
        android:textSize="20sp"
        android:gravity="center_vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

4.MainActivity.java

package mydemo.mycom.demo2;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;


import mydemo.mycom.demo2.dao.UserDao;
import mydemo.mycom.demo2.entity.UserInfo;
import mydemo.mycom.demo2.service.LoginService;


public class Home extends ActionBarActivity implements View.OnClickListener {

    private ListView lv;
    private Button btn_home_to_login;
    private Button btn_exit;
    private List<UserInfo> list;
    // 设置一个最大的数据条数,超过即不再加载
    private int pageSize=10; //每次获取多少条数据
    // 最后可见条目的索引
    private int pages;//总共有多少页
    private boolean loadfinished = true;
    private MyAdapter myAdapter;
    private View footer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        btn_home_to_login = (Button)findViewById(R.id.btn_home_to_login);
        btn_exit = (Button)findViewById(R.id.btn_exit);
        lv = (ListView)findViewById(R.id.lv);
        btn_home_to_login.setOnClickListener(this);
        btn_exit.setOnClickListener(this);

        footer = getLayoutInflater().inflate(R.layout.activity_footer,null);

        UserDao dao = new UserDao(this);
        list = dao.getUserInfo(1,10);

        int total = dao.getTotal();

        System.out.println(total+"===================================");

        pages = total%pageSize==0 ? total/pageSize : total/pageSize+1;

        lv.setOnScrollListener(new MyOnScrollListener());

        myAdapter = new MyAdapter();
        //添加页脚(放在ListView最后)
        lv.addFooterView(footer);
        lv.setAdapter(myAdapter);
        lv.removeFooterView(footer);

        lv.setOnItemClickListener(new MyItemClickListener());

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId())
        {
            case R.id.btn_home_to_login:
                Intent intent = new Intent();
                intent.setClass(Home.this,Register.class);
                startActivity(intent);
                break;
            case R.id.btn_exit:
                //清除登录数据
                LoginService.removeLoginInfo(this);
                Toast.makeText(this,"退出成功",Toast.LENGTH_SHORT).show();

                Intent toLogin = new Intent();
                toLogin.setClass(Home.this,MainActivity.class);
                startActivity(toLogin);
                break;
        }
    }


    public class MyAdapter extends BaseAdapter
    {
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            UserInfo user = list.get(i);

            View itemview = View.inflate(Home.this,R.layout.activity_item,null);

            TextView tv_id = (TextView)itemview.findViewById(R.id.tv_id);
            TextView tv_username = (TextView)itemview.findViewById(R.id.tv_username);
            TextView tv_password = (TextView)itemview.findViewById(R.id.tv_password);

            tv_id.setText(user.getId()+"");
            tv_username.setText(user.getUsername());
            tv_password.setText(user.getPassword());
            return itemview;
        }
    }


    public class MyItemClickListener implements AdapterView.OnItemClickListener
    {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            ListView lView = (ListView)lv;
            TextView tv_id = (TextView)view.findViewById(R.id.tv_id);
            TextView tv_username = (TextView)view.findViewById(R.id.tv_username);
            TextView tv_password = (TextView)view.findViewById(R.id.tv_password);
            String id = tv_id.getText().toString();
            String username = tv_username.getText().toString();
            String password = tv_password.getText().toString();
            Toast.makeText(getApplicationContext(), id+","+username, Toast.LENGTH_SHORT).show();
            //不同的activity之间的传值
            Intent intent = new Intent();
            intent.putExtra("username",username);
            intent.putExtra("password",password);
            intent.putExtra("id",id);
            intent.setClass(Home.this,Edit.class);
            startActivity(intent);
        }
    }

    public class MyOnScrollListener implements AbsListView.OnScrollListener
    {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int lastItemIndex = lv.getLastVisiblePosition(); //获取当前屏幕最后的Item的id
            System.out.println("====lastItemIndex:"+lastItemIndex);
            System.out.println("====totalItemCount:"+totalItemCount);
            if(lastItemIndex>0&&(lastItemIndex+1)==totalItemCount) //达到数据的最后一条记录
            {
                //当前页
                int currentpage = totalItemCount%pageSize==0 ? totalItemCount /pageSize :totalItemCount /pageSize+1;
                final int nextpage = currentpage +1; //下一页
                System.out.println("================currentpage:"+currentpage);
                System.out.println("================nextpage:"+nextpage);
                if(nextpage<=pages && loadfinished)
                {
                    loadfinished = false;
                    lv.addFooterView(footer);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try{
                                Thread.sleep(3000);
                            }
                             catch (Exception e)
                             {

                             }
                            UserDao dao = new UserDao(Home.this);

                            List<UserInfo> result = dao.getUserInfo(nextpage,pageSize);
                            handler.sendMessage(handler.obtainMessage(100,result));
                        }
                    }).start();
                }
            }
        }


        Handler handler = new Handler() {

            public void handleMessage(Message msg)
            {
                list.addAll((List<UserInfo>)msg.obj);
                //告诉ListView数据已经发生改变,要求ListView更新界面显示
                myAdapter.notifyDataSetChanged();
                if(lv.getFooterViewsCount()>0)
                {
                    lv.removeFooterView(footer);
                }
                loadfinished = true;
;            }

        };
    }



}

5.DAO.java

public List<UserInfo> getUserInfo(int pageIndex,int pageSize)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        List<UserInfo> list = new ArrayList<UserInfo>();

        String sql = "select * from user order by id asc limit "+(pageIndex-1)*pageSize+","+pageSize;
        System.out.println("sql=======:"+sql+",pageIndex:"+pageIndex);

        Cursor cursor = db.rawQuery("select * from user order by id asc limit ?,?",new String[]{((pageIndex-1)*pageSize)+"",pageSize+""});
        while(cursor.moveToNext())
        {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String username = cursor.getString(cursor.getColumnIndex("username"));
            String password = cursor.getString(cursor.getColumnIndex("password"));

            UserInfo userInfo = new UserInfo(id,username,password);
            list.add(userInfo);
        }
        cursor.close();
        db.close();
        return list;

    }

5.Entity.java

package mydemo.mycom.demo2.entity;


public class UserInfo {
    private int id;
    private String username;
    private String password;

    public UserInfo()
    { }

    public UserInfo(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

posted @ 2015-05-20 09:20  大空白纸  阅读(290)  评论(0编辑  收藏  举报