Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android實現簡單的分批加載ListView

Android實現簡單的分批加載ListView

編輯:關於Android編程

每次滑動至底端,從數據庫中獲取10條數據,並加載於ListView中

數據庫

package com.example.listviewbatchloading; 
 
import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteDatabase.CursorFactory; 
import android.database.sqlite.SQLiteOpenHelper; 
 
public class PersonDb extends SQLiteOpenHelper { 
 
  public PersonDb(Context context) { 
    super(context, "creature", null, 1); 
    // TODO Auto-generated constructor stub 
  } 
 
  @Override 
  public void onCreate(SQLiteDatabase db) { 
    // TODO Auto-generated method stub 
    db.execSQL("create table people(_id integer primary key autoincrement,name char,number char)"); 
  } 
 
  @Override 
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // TODO Auto-generated method stub 
    db.execSQL("drop table people"); 
    onCreate(db); 
  } 
 
} 

數據庫的業務封裝,其中獲取更多數據的是核心代碼

package com.example.listviewbatchloading; 
 
/** 
 * 數據庫的業務封裝類 
 */ 
 
import java.util.ArrayList; 
import java.util.List; 
 
import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
 
public class PersonList { 
   
  PersonDb personDb; 
   
  public PersonList(Context context){ 
    this.personDb = new PersonDb(context); 
  } 
   
  /** 
   *   獲取一定條目的數據 
   * @param startIndex 
   *   開始取數據的位置 
   * @param num 
   *   取多少條數據 
   */ 
  public List<Person> getMoreDatas(int startIndex,int num){ 
     
    List<Person> list = new ArrayList<Person>(); 
    SQLiteDatabase db = personDb.getWritableDatabase(); 
    Cursor cursor = db.rawQuery("select name,number from people order by _id desc limit ?,?", 
        new String[]{startIndex + "",num + ""}); 
     
    while(cursor.moveToNext()){ 
      Person person = new Person(); 
      person.setName(cursor.getString(cursor.getColumnIndex("name"))); 
      person.setNumber(cursor.getString(cursor.getColumnIndex("number"))); 
      list.add(person); 
    } 
     
    cursor.close(); 
    db.close(); 
     
     
    return list; 
     
  } 
   
  /** 
   *   添加數據庫條目 
   * @param name 
   * @param number 
   */ 
  public void add(String name,String number){ 
     
    SQLiteDatabase db = personDb.getWritableDatabase(); 
     
    ContentValues cv = new ContentValues(); 
    cv.put("name", name); 
    cv.put("number", number); 
     
    db.insert("people", null, cv); 
    db.close(); 
  } 
   
} 

功能實現

package com.example.listviewbatchloading; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AbsListView; 
import android.widget.AbsListView.OnScrollListener; 
import android.widget.BaseAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 
 
public class MainActivity extends Activity { 
   
  private ListView lv ; 
  private List<Person> datas = new ArrayList<Person>(); 
  private static int PERPAGE = 10; //每頁加載數目 
  private static final int FINISH = 0;//數據加載完成 
  private List<Person> moreDatas;//每次加載的數據 
  private MyAdapter adapter; 
  private PersonList personList ; 
   
  //若數據較多,耗時較長,數據加載完成時,發送FINISH至handler,並通知ListView更新數據 
  private Handler handler = new Handler(){ 
    public void handleMessage(android.os.Message msg) { 
       
      switch (msg.what) { 
      case FINISH: 
        if (moreDatas.size() != 0) { 
          System.out.println(moreDatas.toString()); 
          adapter.notifyDataSetChanged(); 
        }else { 
          Toast.makeText(MainActivity.this, "沒有更多數據", Toast.LENGTH_SHORT).show(); 
        } 
        break; 
 
      default: 
        break; 
      } 
       
       
    }; 
  }; 
   
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    initView(); 
    initData(); 
    initEvent(); 
  } 
  /** 
   *   為ListView添加滾動監聽事件,但滾動至最後一行時,加載更多數據 
   */ 
  private void initEvent() { 
    lv.setOnScrollListener(new OnScrollListener() { 
       
      @Override 
      public void onScrollStateChanged(AbsListView view, int scrollState) { 
        // TODO Auto-generated method stub 
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { 
          int lastVisiblePosition = lv.getLastVisiblePosition(); 
          if (lastVisiblePosition == datas.size() - 1) { 
            initData(); 
            System.out.println("加載更多數據"); 
          } 
        } 
      } 
       
      @Override 
      public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 
        // TODO Auto-generated method stub 
         
      } 
    }); 
  } 
 
  private void initView() { 
     
    setContentView(R.layout.activity_main); 
     
    lv = (ListView) findViewById(R.id.lv); 
    personList = new PersonList(getApplicationContext()); 
    adapter = new MyAdapter(); 
    lv.setAdapter(adapter); 
  } 
   
  /** 
   * 在子線程中加載數據,避免主線程阻塞 
   */ 
  private void initData() { 
    new Thread() { 
 
      public void run() { 
 
        // 加載更多數據 
        moreDatas = personList.getMoreDatas(datas.size(), PERPAGE); 
 
        datas.addAll(moreDatas);// 把一個容器的所有數據加進來 
        // 取數據完成,發消息通知取數據完成 
        handler.obtainMessage(FINISH).sendToTarget(); 
 
      }; 
    }.start(); 
  } 
   
  private class ItemView{ 
    private TextView tv_name; 
    private TextView tv_num; 
  } 
   
  /** 
   *   ListView的適配器 
   * @author lian 
   * 
   */ 
  private class MyAdapter extends BaseAdapter{ 
 
    @Override 
    public int getCount() { 
      // TODO Auto-generated method stub 
      return datas.size(); 
    } 
 
    @Override 
    public Object getItem(int position) { 
      // TODO Auto-generated method stub 
      return null; 
    } 
 
    @Override 
    public long getItemId(int position) { 
      // TODO Auto-generated method stub 
      return 0; 
    } 
 
    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
       
      ItemView itemView = null; 
      if (convertView == null) { 
        itemView = new ItemView(); 
        convertView = View.inflate(getApplicationContext(), R.layout.item_lv, null); 
        itemView.tv_name = (TextView) convertView.findViewById(R.id.tv_name); 
        itemView.tv_num = (TextView) convertView.findViewById(R.id.tv_num); 
        convertView.setTag(itemView); 
      }else { 
        itemView = (ItemView) convertView.getTag(); 
      } 
       
      Person person = datas.get(position); 
      itemView.tv_name.setText(person.getName()); 
      itemView.tv_num.setText(person.getNumber()); 
       
      return convertView; 
    } 
     
  } 
   
} 

其他Person的JavaBean,以及布局文件,不在贅述

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved