android分頁查詢功能工具類的實現

在一個項目中,常常需要頻繁的分頁,所以有必要實現一個封裝的類來統一管理實現。

首先看下效果圖:

 

 

 從上圖我們可以看出,這裡是將listview中的數據通過底下的分頁工具實現分頁顯示。那我們接下來先貼出代碼:

[html]
1、實現佈局,這裡有兩個佈局文件,第一個主佈局文件main.xml 
 
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android" 
                android:id="@+id/whole_region" 
                android:layout_width="fill_parent" 
                android:layout_height="fill_parent" 
                android:orientation="vertical" > 
 
                <HorizontalScrollView 
                    android:id="@+id/HorizontalScrollView01" 
                    android:layout_width="fill_parent" 
                    android:layout_height="wrap_content" 
                    android:layout_above="@+id/pagebtn" 
                    android:layout_alignParentTop="true" > 
 
                    <LinearLayout 
                        android:layout_width="wrap_content" 
                        android:layout_height="fill_parent" 
                        android:orientation="vertical" > 
 
                        <LinearLayout 
                            android:id="@+id/list_view_title" 
                            android:layout_width="wrap_content" 
                            android:layout_height="wrap_content" 
                            android:orientation="horizontal">                         
                        </LinearLayout> 
 
                        <ListView 
                            android:id="@+id/list" 
                            android:layout_width="wrap_content" 
                            android:layout_height="wrap_content" 
                            android:fadeScrollbars="false" > 
                        </ListView> 
                    </LinearLayout> 
                </HorizontalScrollView> 
 
                <LinearLayout 
                    android:id="@id/pagebtn" 
                    android:layout_width="fill_parent" 
                    android:layout_height="wrap_content" 
                    android:layout_alignParentBottom="true" 
                    android:orientation="vertical" > 
 
                    <include layout="@layout/pagebutton" /> 
                </LinearLayout> 
            </RelativeLayout> 
 
第二個佈局文件pagebutton.xml.這個文件嵌套在第一個主文件中。 
1、實現佈局,這裡有兩個佈局文件,第一個主佈局文件main.xml

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/whole_region"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <HorizontalScrollView
                    android:id="@+id/HorizontalScrollView01"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_above="@+id/pagebtn"
                    android:layout_alignParentTop="true" >

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

                        <LinearLayout
                            android:id="@+id/list_view_title"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">                       
                        </LinearLayout>

                        <ListView
                            android:id="@+id/list"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fadeScrollbars="false" >
                        </ListView>
                    </LinearLayout>
                </HorizontalScrollView>

                <LinearLayout
                    android:id="@id/pagebtn"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:orientation="vertical" >

                    <include layout="@layout/pagebutton" />
                </LinearLayout>
            </RelativeLayout>

第二個佈局文件pagebutton.xml.這個文件嵌套在第一個主文件中。[html]
<pre class="html" name="code"><?xml version="1.0" encoding="utf-8"?> 
<merge xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" android:layout_height="fill_parent"> 
    <TableLayout android:id="@+id/TableLayout1" 
        android:layout_width="fill_parent" android:layout_height="wrap_content" 
        android:stretchColumns="0,1,2,3,4,5,6,7" android:shrinkColumns="0,1,2,3,4,5,6,7"  
        android:paddingTop="5dip" android:paddingLeft="5dip" android:paddingRight="5dip"> 
        <TableRow> 
            <TextView android:text="共" android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textSize="18sp" /> 
            <TextView android:id="@+id/total_page_num" android:minWidth="30dp" 
                android:layout_width="wrap_content" android:layout_height="wrap_content" 
                android:textColor="#C71585" 
                android:textSize="18sp" /> 
            <TextView android:text="頁" android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textSize="18sp" /> 
            <TextView android:id="@+id/total_record_num" 
                android:minWidth="60dp" android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textColor="#C71585" android:textSize="18sp" /> 
            <TextView android:text="條," android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textSize="18sp" /> 
            <TextView android:text="每頁" android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textSize="18sp" /> 
            <TextView android:id="@+id/record_num_each_page" 
                android:layout_width="wrap_content"  
<pre class="html" name="code"><?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent">
 <TableLayout android:id="@+id/TableLayout1"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:stretchColumns="0,1,2,3,4,5,6,7" android:shrinkColumns="0,1,2,3,4,5,6,7"
  android:paddingTop="5dip" android:paddingLeft="5dip" android:paddingRight="5dip">
  <TableRow>
   <TextView android:text="共" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textSize="18sp" />
   <TextView android:id="@+id/total_page_num" android:minWidth="30dp"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textColor="#C71585"
    android:textSize="18sp" />
   <TextView android:text="頁" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textSize="18sp" />
   <TextView android:id="@+id/total_record_num"
    android:minWidth="60dp" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textColor="#C71585" android:textSize="18sp" />
   <TextView android:text="條," android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textSize="18sp" />
   <TextView android:text="每頁" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textSize="18sp" />
   <TextView android:id="@+id/record_num_each_page"
    android:layout_width="wrap_content" [html]
android:layout_height="wrap_content"                       
                                    android:layout_height="wrap_content"                      [html]
                                    android:textColor="#C71585" 
                android:textSize="18sp" /> 
            <TextView android:text="條" android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textSize="18sp" /> 
        </TableRow> 
    </TableLayout> 
    <TableLayout android:id="@+id/TableLayout1" 
        android:layout_width="fill_parent" android:layout_height="wrap_content" 
        android:stretchColumns="0,1,2,3,4,5,6,7" android:shrinkColumns="0,1,2,3,4,5,6,7,8" android:paddingTop="5dip"> 
        <TableRow> 
            <Button android:id="@+id/first_page" android:text="|<" 
                android:layout_width="wrap_content" android:layout_height="wrap_content" 
                android:textSize="18sp" /> 
            <Button android:id="@+id/page_up" android:text=" < " 
                android:layout_width="wrap_content" android:layout_height="wrap_content" 
                android:textSize="18sp" /> 
            <Button android:id="@+id/page_down" android:text=" > " 
                android:layout_width="wrap_content" android:layout_height="wrap_content" 
                android:textSize="18sp" /> 
            <Button android:id="@+id/last_page" android:text=">|" 
                android:layout_width="wrap_content" android:layout_height="wrap_content" 
                android:textSize="18sp" /> 
            <TextView android:text="第" android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textSize="18sp" /> 
            <EditText android:id="@+id/current_page" android:maxWidth="40dip" 
                android:singleLine="true" android:layout_width="wrap_content" 
                android:layout_height="wrap_content"  android:textColor="#C71585" android:textSize="18sp" /> 
            <TextView android:text="頁" android:layout_width="wrap_content" 
                android:layout_height="wrap_content" android:textSize="18sp" /> 
            <Button android:id="@+id/to_page" android:text="轉到" 
                android:layout_width="wrap_content" android:layout_height="wrap_content" 
                android:textSize="18sp" /> 
        </TableRow> 
    </TableLayout> 
</merge> 
                                    android:textColor="#C71585"
    android:textSize="18sp" />
   <TextView android:text="條" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textSize="18sp" />
  </TableRow>
 </TableLayout>
 <TableLayout android:id="@+id/TableLayout1"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:stretchColumns="0,1,2,3,4,5,6,7" android:shrinkColumns="0,1,2,3,4,5,6,7,8" android:paddingTop="5dip">
  <TableRow>
   <Button android:id="@+id/first_page" android:text="|<"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textSize="18sp" />
   <Button android:id="@+id/page_up" android:text=" < "
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textSize="18sp" />
   <Button android:id="@+id/page_down" android:text=" > "
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textSize="18sp" />
   <Button android:id="@+id/last_page" android:text=">|"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textSize="18sp" />
   <TextView android:text="第" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textSize="18sp" />
   <EditText android:id="@+id/current_page" android:maxWidth="40dip"
    android:singleLine="true" android:layout_width="wrap_content"
    android:layout_height="wrap_content"  android:textColor="#C71585" android:textSize="18sp" />
   <TextView android:text="頁" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:textSize="18sp" />
   <Button android:id="@+id/to_page" android:text="轉到"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textSize="18sp" />
  </TableRow>
 </TableLayout>
</merge>

第二步:新建一個activity,用來顯示界面

[java]
public class BuilderList1 extends QueryContextActivity { 
    private PagedQueryResultHelper pagedQueryResultHelper; 
    private Map<String, Object> params; 
    private ListView list; 
    private List<Integer> columnWidths; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        // TODO Auto-generated method stub  
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.mynotifylist); 
        setOnClickListener(); 
         
 
        columnWidths = new ArrayList<Integer>(); 
        int weight = this.getWindowManager().getDefaultDisplay().getWidth(); 
        columnWidths.add(weight); 
 
        pagedQueryResultHelper = new PagedQueryResultHelper(this); 
        pagedQueryResultHelper.setTitleCellWidth(columnWidths); 
public class BuilderList1 extends QueryContextActivity {
 private PagedQueryResultHelper pagedQueryResultHelper;
 private Map<String, Object> params;
 private ListView list;
 private List<Integer> columnWidths;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.mynotifylist);
  setOnClickListener();
  

  columnWidths = new ArrayList<Integer>();
  int weight = this.getWindowManager().getDefaultDisplay().getWidth();
  columnWidths.add(weight);

  pagedQueryResultHelper = new PagedQueryResultHelper(this);
  pagedQueryResultHelper.setTitleCellWidth(columnWidths);[java]
//這個方法是用來查詢數據並顯示在LISTVIEW中的,我們這次的重點不在這裡,我隻列出不詳講,有興趣的朋友可以自己研究下listview               query(); 
                  //這個方法是用來查詢數據並顯示在LISTVIEW中的,我們這次的重點不在這裡,我隻列出不詳講,有興趣的朋友可以自己研究下listview          query();[java]
    } 
 
    <p>        protected void query() { 
                params = new HashMap<String, Object>(); 
                params.put("userName", UserInfo.getUserName());</p><p>                pagedQueryResultHelper.setQueryParams("getBuilderList", params, 
               "startNum", "endNum", "MyNotifyList", R.array.build_list_name, R.array.build_list); 
             if (pagedQueryResultHelper.initialQuery() == null) { 
                             new AlertDialog.Builder(this) 
                            .setTitle(R.string.message_title) 
                            .setMessage("沒有查詢到相關信息,請返回!") 
                            .setPositiveButton(R.string.OK_text, null) 
                            .setPositiveButton(R.string.OK_text, 
                           new DialogInterface.OnClickListener() { 
                       @Override 
                    public void onClick(DialogInterface dialog, int which) {</p><p>                            BuilderList1.this.finish();</p><p>                     } }).show(); 
  };</p><p>             list = (ListView) findViewById(R.id.list);</p><p>             list.setOnItemClickListener(new OnItemClickListener() { 
             @Override 
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long arg3) {</p><p>                  List<Map<String, Object>> data = pagedQueryResultHelper .getWholeResult(); 
                  Intent intent = new Intent(BuilderList1.this,FloorInfo.class); 
                  intent.putExtra("value", (Serializable) data.get(index)); 
                  intent.putExtra("buildid", data.get(index).get("BUILDID").toString()); 
                  startActivity(intent); }}); 
 }</p><p>             @Override 
            public void onClick(View arg0) { 
              switch (arg0.getId()) { 
              case R.id.first_page: 
               pagedQueryResultHelper.firstPage(); 
                  break; 
              case R.id.page_down: 
               pagedQueryResultHelper.pageDown(); 
                  break; 
              case R.id.page_up: 
               pagedQueryResultHelper.pageUp(); 
                break; 
              case R.id.last_page: 
               pagedQueryResultHelper.lastPage(); 
                 break; 
              case R.id.to_page: 
               pagedQueryResultHelper.toPage(); 
                break; 
        } 
    }</p><p>        @Override 
              protected void clear() { 
   }</p><p>       @Override 
    protected void setOnClickListener() { 
   }</p><p>}</p><p> </p>第三步:實現這個工具類,這個類代碼有些多 
 }

 <p>        protected void query() {
                params = new HashMap<String, Object>();
                params.put("userName", UserInfo.getUserName());</p><p>                pagedQueryResultHelper.setQueryParams("getBuilderList", params,
               "startNum", "endNum", "MyNotifyList", R.array.build_list_name, R.array.build_list);
             if (pagedQueryResultHelper.initialQuery() == null) {
                             new AlertDialog.Builder(this)
                            .setTitle(R.string.message_title)
                            .setMessage("沒有查詢到相關信息,請返回!")
                            .setPositiveButton(R.string.OK_text, null)
                            .setPositiveButton(R.string.OK_text,
                           new DialogInterface.OnClickListener() {
                       @Override
                    public void onClick(DialogInterface dialog, int which) {</p><p>                            BuilderList1.this.finish();</p><p>                     } }).show();
  };</p><p>             list = (ListView) findViewById(R.id.list);</p><p>             list.setOnItemClickListener(new OnItemClickListener() {
             @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long arg3) {</p><p>                  List<Map<String, Object>> data = pagedQueryResultHelper .getWholeResult();
                  Intent intent = new Intent(BuilderList1.this,FloorInfo.class);
                  intent.putExtra("value", (Serializable) data.get(index));
                  intent.putExtra("buildid", data.get(index).get("BUILDID").toString());
                  startActivity(intent); }});
 }</p><p>             @Override
            public void onClick(View arg0) {
              switch (arg0.getId()) {
              case R.id.first_page:
               pagedQueryResultHelper.firstPage();
                  break;
              case R.id.page_down:
               pagedQueryResultHelper.pageDown();
                  break;
              case R.id.page_up:
               pagedQueryResultHelper.pageUp();
                break;
              case R.id.last_page:
               pagedQueryResultHelper.lastPage();
                 break;
              case R.id.to_page:
               pagedQueryResultHelper.toPage();
                break;
        }
    }</p><p>        @Override
              protected void clear() {
   }</p><p>       @Override
    protected void setOnClickListener() {
   }</p><p>}</p><p> </p>第三步:實現這個工具類,這個類代碼有些多[java]
<pre class="java" name="code">package org.Base.Utils; 
 
import java.util.Arrays; 
import java.util.List; 
import java.util.Map; 
 
import org.Base.Activities.QueryContextActivity; 
import org.Base.Container.DataTableAdapter; 
import org.Base.Container.myListViewTitle; 
import org.Base.Webservice.WSObjectListUtil; 
import org.Base.Webservice.WSObjectMapUtil; 
import org.Base.Webservice.WSObjectUtil; 
import org.Base.Webservice.WSUtil; 
import org.Base.Webservice.WebServiceConfig; 
import org.DigitalCM.R; 
import org.ksoap2.serialization.SoapObject; 
 
import android.app.AlertDialog; 
import android.util.Log; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.TextView; 
 
public class PagedQueryResultHelper { 
    private final static int initialFromRecordNum = 1;//每頁從第1條開始  
    private final static int initialToRecordNum = 20;//每頁可以顯示20條  
 
    public PagedQueryResultHelper(QueryContextActivity contextActivity) {//構造函數用來初始化,主要是用來接收傳過來的activity做為上下文對象  
        this.contextActivity = contextActivity; 
 
        findViews();//調用此方法找到傳過來的activity的控件對象  
        setOnClickListener();//給控件設置監聽  
        if (currentPageText != null) {//如果所有頁面隻有一頁,那就隻顯示一頁  
            setCurrentPage(1); 
        } 
    } 
 
    public List<List<String>> initialQuery() { 
        setRecordNumEachPage(initialToRecordNum – initialFromRecordNum + 1);//設置每頁的記錄條數  
        return query(initialFromRecordNum, initialToRecordNum); 
 
    } 
 
    public List<List<String>> initialQuery01() { 
        return query(methodName, params); 
    } 
 
    private void setCurrentPage(int currentPage) {//設置當前頁  
        this.currentPage = currentPage; 
        currentPageText.setText(String.valueOf(currentPage)); 
    } 
 
    public void setMarkable(boolean bMarkable) {//這個是用來標記記錄的  
        this.bMarkable = bMarkable; 
    } 
 
    public void setRecordNumEachPage(int recordNumEachPage) {);//設置每頁的記錄條數  
        this.recordNumEachPage = recordNumEachPage; 
        recordNumEachPageText.setText(String.valueOf(recordNumEachPage)); 
    } 
 
    public void setTotalRecord(int totalRecord) {//設置總記錄數  
        this.totalRecord = totalRecord; 
        totalRecordNumText.setText(String.valueOf(totalRecord)); 
        getTotalPageNumText(); 
    } 
 
    private QueryContextActivity contextActivity; 
    private TextView totalPageNumText; 
    private TextView totalRecordNumText; 
    private TextView recordNumEachPageText; 
    private Button firstPage; 
    private Button pageDown; 
    private Button pageUp; 
    private Button lastPage; 
    private EditText currentPageText; 
    private Button toPage; 
 
    private int totalPage; 
    private int totalRecord; 
    private int recordNumEachPage; 
    private int currentPage; 
    private String fromRecordNumField; 
    private String toRecordNumField; 
    private String methodName; 
    private Map<String, Object> params; 
    private String contentTableName; 
    // private String countTableName;  
    private int headerNameId; 
    private int headerId; 
    private List<Integer> columnWidths = null; 
    private boolean bSetTitleValue = false; 
    private List<Map<String, Object>> wholeresult = null; 
    private List<List<String>> rows = null; 
    private boolean bMarkable = false; 
    private DataTableAdapter dataTableAdapter; 
 
    public void setQueryParams(String methodName, Map<String, Object> params, 
            String fromRecordNumField, String toRecordNumField, 
            String contentTableName, int headerNameId, int headerId) { 
        this.methodName = methodName; 
        this.params = params; 
        this.fromRecordNumField = fromRecordNumField; 
        this.toRecordNumField = toRecordNumField; 
        this.contentTableName = contentTableName; 
        // this.countTableName = countTableName;  
        this.headerNameId = headerNameId; 
        this.headerId = headerId; 
    } 
 
    public void setQueryParams(String methodName, Map<String, Object> params, 
            String fromRecordNumField, String toRecordNumField, 
            String contentTableName) { 
        this.methodName = methodName; 
        this.params = params; 
        this.fromRecordNumField = fromRecordNumField; 
        this.toRecordNumField = toRecordNumField; 
        this.contentTableName = contentTableName; 
        // this.countTableName = countTableName;  
 
    } 
 
    public void setQueryParams(String methodName, Map<String, Object> params, 
            String contentTableName, int headerNameId, int headerId) { 
        this.methodName = methodName; 
        this.params = params; 
 
        this.contentTableName = contentTableName; 
 
        this.headerNameId = headerNameId; 
        this.headerId = headerId; 
 
    } 
 
    public void setTitleCellWidth(List<Integer> columnWidths) { 
        this.columnWidths = columnWidths; 
    } 
 
    /*
     * public int getCurrentPage(){ return currentPage; }
     */ 
 
    private void findViews() { 
        totalPageNumText = (TextView) contextActivity 
                .findViewById(R.id.total_page_num); 
        totalRecordNumText = (TextView) contextActivity 
                .findViewById(R.id.total_record_num); 
        recordNumEachPageText = (TextView) contextActivity 
                .findViewById(R.id.record_num_each_page); 
        firstPage = (Button) contextActivity.findViewById(R.id.first_page); 
        pageDown = (Button) contextActivity.findViewById(R.id.page_down); 
        pageUp = (Button) contextActivity.findViewById(R.id.page_up); 
        lastPage = (Button) contextActivity.findViewById(R.id.last_page); 
        currentPageText = (EditText) contextActivity 
                .findViewById(R.id.current_page); 
        toPage = (Button) contextActivity.findViewById(R.id.to_page); 
    } 
 
    private void setOnClickListener() { 
        if (firstPage != null) { 
            firstPage.setOnClickListener(contextActivity); 
        } 
        if (pageDown != null) { 
            pageDown.setOnClickListener(contextActivity); 
        } 
        if (pageUp != null) { 
            pageUp.setOnClickListener(contextActivity); 
        } 
        if (lastPage != null) { 
            lastPage.setOnClickListener(contextActivity); 
        } 
        if (toPage != null) { 
            toPage.setOnClickListener(contextActivity); 
        } 
    } 
 
    private void getRecordNumEachPageText() { 
        try { 
            recordNumEachPage = Integer.parseInt(recordNumEachPageText 
                    .getText().toString()); 
        } catch (NumberFormatException e) { 
            Log.e("NumberFormatException", e.getMessage()); 
        } 
    } 
 
    private boolean outOfEachPageRange() { 
        recordNumEachPage = Integer.parseInt(recordNumEachPageText.getText() 
                .toString()); 
        if (recordNumEachPage > 20 || recordNumEachPage < 1) { 
            return true; 
        } 
        return false; 
    } 
 
    private void getTotalPageNumText() { 
        getRecordNumEachPageText(); 
        if (recordNumEachPage == 0) 
            return; 
        if (totalRecord == 0) { 
            totalPage = 0; 
            totalPageNumText.setText(String.valueOf(0)); 
            return; 
        } 
        if (totalRecord % recordNumEachPage == 0) {//java中分頁常用到的計算公式  
            totalPage = totalRecord / recordNumEachPage; 
        } else { 
            totalPage = totalRecord / recordNumEachPage + 1; 
        } 
        totalPageNumText.setText(String.valueOf(totalPage)); 
    } 
 
    public void pageDown() { 
        if (outOfEachPageRange()) { 
            AlertDialog.Builder dialog = new AlertDialog.Builder( 
                    contextActivity); 
            dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!") 
                    .setPositiveButton("確認", null).show(); 
            return; 
        } 
        if (currentPage != totalPage) { 
            setCurrentPage(++currentPage); 
            getTotalPageNumText(); 
            query(recordNumEachPage * (currentPage – 1) + 1, recordNumEachPage 
                    * currentPage); 
        } 
    } 
 
    public void pageUp() { 
        if (outOfEachPageRange()) { 
            AlertDialog.Builder dialog = new AlertDialog.Builder( 
                    contextActivity); 
            dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!") 
                    .setPositiveButton("確認", null).show(); 
            return; 
        } 
        if (currentPage != 1 && currentPage != 0) { 
            setCurrentPage(–currentPage); 
            getTotalPageNumText(); 
            query(recordNumEachPage * (currentPage – 1) + 1, recordNumEachPage 
                    * currentPage); 
        } 
    } 
 
    public void firstPage() { 
        if (outOfEachPageRange()) { 
            AlertDialog.Builder dialog = new AlertDialog.Builder( 
                    contextActivity); 
            dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!") 
                    .setPositiveButton("確認", null).show(); 
            return; 
        } 
        getTotalPageNumText(); 
        if (totalPage > 1) { 
            setCurrentPage(1); 
            query(1, recordNumEachPage); 
        } 
    } 
 
    public void lastPage() { 
        if (outOfEachPageRange()) { 
            AlertDialog.Builder dialog = new AlertDialog.Builder( 
                    contextActivity); 
            dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!") 
                    .setPositiveButton("確認", null).show(); 
            return; 
        } 
        getTotalPageNumText(); 
        if (totalPage != 1 && totalPage != 0) { 
            setCurrentPage(totalPage); 
            query(recordNumEachPage * (totalPage – 1) + 1, totalRecord); 
        } 
    } 
 
    public void toPage() { 
        if (outOfEachPageRange()) { 
            AlertDialog.Builder dialog = new AlertDialog.Builder( 
                    contextActivity); 
            dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!") 
                    .setPositiveButton("確認", null).show(); 
            return; 
        } 
        try { 
            currentPage = Integer 
                    .parseInt(currentPageText.getText().toString()); 
        } catch (NumberFormatException e) { 
            Log.e("NumberFormatException", e.getMessage()); 
            return; 
        } 
        getTotalPageNumText(); 
        query(recordNumEachPage * (currentPage – 1) + 1, recordNumEachPage 
                * currentPage); 
        currentPageText.setText(String.valueOf(currentPage)); 
    } 
 
    public List<List<String>> query(int fromRecordNum, int toRecordNum) { 
        return query(methodName, params, fromRecordNumField, toRecordNumField, 
                fromRecordNum, toRecordNum); 
    } 
 
    private List<List<String>> query(String methodName, 
            Map<String, Object> params, String fromRecordNumField, 
            String toRecordNumField, int fromRecordNum, int toRecordNum) { 
        params.put(fromRecordNumField, fromRecordNum); 
        params.put(toRecordNumField, toRecordNum); 
 
        return query(methodName, params); 
    } 
 
    public List<Map<String, Object>> getWholeResult() { 
        return wholeresult; 
    } 
 
    public List<Map<String, Object>> getResult() { 
        return wholeresult; 
    } 
 
    public List<Boolean> getCheckBoxState() { 
        return dataTableAdapter.getCheckBoxState(); 
    } 
 
    public List<List<String>> query(String methodName, 
            Map<String, Object> params) {//此方法要重點註意,因為這裡是根據webservice查詢到的數據,所以要傳遞來方法和參數  
        SoapObject result = null; 
 
        if (methodName == null) { 
            if (bSetTitleValue == false) {//下面是實現listview的標題顯示  
                bSetTitleValue = true; 
                myListViewTitle listViewTitle = new myListViewTitle( 
                        contextActivity); 
                if (this.columnWidths != null) { 
                    listViewTitle.setTitleCellWidth(this.columnWidths); 
                } 
                List<String> headerList = Arrays.asList(contextActivity 
                        .getResources().getStringArray(headerId)); 
                listViewTitle.setTitleCellValue(headerList); 
            } 
            return null; 
        } 
 
        try { 
            result = WSUtil.getSoapObjectByCallingWS(//這裡是android調用webservice的典型方法  
                    WebServiceConfig.NAMESPACE, methodName, params, 
                    WebServiceConfig.wsdl); 
        } catch (Exception e) { 
            new AlertDialog.Builder(contextActivity) 
                    .setTitle(R.string.message_title) 
                    .setMessage(R.string.connection_error) 
                    .setPositiveButton(R.string.OK_text, null).show(); 
            Log.e("Exception", e.getMessage()); 
        } 
 
        if (result == null) {//如果從webservice得到的結果為null,那我們就找到listview,並賦空值,將分頁的顯示值設為0  
            ListView list = (ListView) contextActivity.findViewById(R.id.list); 
            list.setAdapter(null); 
            setTotalRecord(0); 
            this.setCurrentPage(0); 
            return null; 
        } 
 
        SoapObject dataSet = WSObjectUtil.getDataSetObject(result);//如果從webservice得到的結果不為空,則轉化成dataSet           
<pre class="java" name="code">package org.Base.Utils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.Base.Activities.QueryContextActivity;
import org.Base.Container.DataTableAdapter;
import org.Base.Container.myListViewTitle;
import org.Base.Webservice.WSObjectListUtil;
import org.Base.Webservice.WSObjectMapUtil;
import org.Base.Webservice.WSObjectUtil;
import org.Base.Webservice.WSUtil;
import org.Base.Webservice.WebServiceConfig;
import org.DigitalCM.R;
import org.ksoap2.serialization.SoapObject;

import android.app.AlertDialog;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class PagedQueryResultHelper {
 private final static int initialFromRecordNum = 1;//每頁從第1條開始
 private final static int initialToRecordNum = 20;//每頁可以顯示20條

 public PagedQueryResultHelper(QueryContextActivity contextActivity) {//構造函數用來初始化,主要是用來接收傳過來的activity做為上下文對象
  this.contextActivity = contextActivity;

  findViews();//調用此方法找到傳過來的activity的控件對象
  setOnClickListener();//給控件設置監聽
  if (currentPageText != null) {//如果所有頁面隻有一頁,那就隻顯示一頁
   setCurrentPage(1);
  }
 }

 public List<List<String>> initialQuery() {
  setRecordNumEachPage(initialToRecordNum – initialFromRecordNum + 1);//設置每頁的記錄條數
  return query(initialFromRecordNum, initialToRecordNum);

 }

 public List<List<String>> initialQuery01() {
  return query(methodName, params);
 }

 private void setCurrentPage(int currentPage) {//設置當前頁
  this.currentPage = currentPage;
  currentPageText.setText(String.valueOf(currentPage));
 }

 public void setMarkable(boolean bMarkable) {//這個是用來標記記錄的
  this.bMarkable = bMarkable;
 }

 public void setRecordNumEachPage(int recordNumEachPage) {);//設置每頁的記錄條數
  this.recordNumEachPage = recordNumEachPage;
  recordNumEachPageText.setText(String.valueOf(recordNumEachPage));
 }

 public void setTotalRecord(int totalRecord) {//設置總記錄數
  this.totalRecord = totalRecord;
  totalRecordNumText.setText(String.valueOf(totalRecord));
  getTotalPageNumText();
 }

 private QueryContextActivity contextActivity;
 private TextView totalPageNumText;
 private TextView totalRecordNumText;
 private TextView recordNumEachPageText;
 private Button firstPage;
 private Button pageDown;
 private Button pageUp;
 private Button lastPage;
 private EditText currentPageText;
 private Button toPage;

 private int totalPage;
 private int totalRecord;
 private int recordNumEachPage;
 private int currentPage;
 private String fromRecordNumField;
 private String toRecordNumField;
 private String methodName;
 private Map<String, Object> params;
 private String contentTableName;
 // private String countTableName;
 private int headerNameId;
 private int headerId;
 private List<Integer> columnWidths = null;
 private boolean bSetTitleValue = false;
 private List<Map<String, Object>> wholeresult = null;
 private List<List<String>> rows = null;
 private boolean bMarkable = false;
 private DataTableAdapter dataTableAdapter;

 public void setQueryParams(String methodName, Map<String, Object> params,
   String fromRecordNumField, String toRecordNumField,
   String contentTableName, int headerNameId, int headerId) {
  this.methodName = methodName;
  this.params = params;
  this.fromRecordNumField = fromRecordNumField;
  this.toRecordNumField = toRecordNumField;
  this.contentTableName = contentTableName;
  // this.countTableName = countTableName;
  this.headerNameId = headerNameId;
  this.headerId = headerId;
 }

 public void setQueryParams(String methodName, Map<String, Object> params,
   String fromRecordNumField, String toRecordNumField,
   String contentTableName) {
  this.methodName = methodName;
  this.params = params;
  this.fromRecordNumField = fromRecordNumField;
  this.toRecordNumField = toRecordNumField;
  this.contentTableName = contentTableName;
  // this.countTableName = countTableName;

 }

 public void setQueryParams(String methodName, Map<String, Object> params,
   String contentTableName, int headerNameId, int headerId) {
  this.methodName = methodName;
  this.params = params;

  this.contentTableName = contentTableName;

  this.headerNameId = headerNameId;
  this.headerId = headerId;

 }

 public void setTitleCellWidth(List<Integer> columnWidths) {
  this.columnWidths = columnWidths;
 }

 /*
  * public int getCurrentPage(){ return currentPage; }
  */

 private void findViews() {
  totalPageNumText = (TextView) contextActivity
    .findViewById(R.id.total_page_num);
  totalRecordNumText = (TextView) contextActivity
    .findViewById(R.id.total_record_num);
  recordNumEachPageText = (TextView) contextActivity
    .findViewById(R.id.record_num_each_page);
  firstPage = (Button) contextActivity.findViewById(R.id.first_page);
  pageDown = (Button) contextActivity.findViewById(R.id.page_down);
  pageUp = (Button) contextActivity.findViewById(R.id.page_up);
  lastPage = (Button) contextActivity.findViewById(R.id.last_page);
  currentPageText = (EditText) contextActivity
    .findViewById(R.id.current_page);
  toPage = (Button) contextActivity.findViewById(R.id.to_page);
 }

 private void setOnClickListener() {
  if (firstPage != null) {
   firstPage.setOnClickListener(contextActivity);
  }
  if (pageDown != null) {
   pageDown.setOnClickListener(contextActivity);
  }
  if (pageUp != null) {
   pageUp.setOnClickListener(contextActivity);
  }
  if (lastPage != null) {
   lastPage.setOnClickListener(contextActivity);
  }
  if (toPage != null) {
   toPage.setOnClickListener(contextActivity);
  }
 }

 private void getRecordNumEachPageText() {
  try {
   recordNumEachPage = Integer.parseInt(recordNumEachPageText
     .getText().toString());
  } catch (NumberFormatException e) {
   Log.e("NumberFormatException", e.getMessage());
  }
 }

 private boolean outOfEachPageRange() {
  recordNumEachPage = Integer.parseInt(recordNumEachPageText.getText()
    .toString());
  if (recordNumEachPage > 20 || recordNumEachPage < 1) {
   return true;
  }
  return false;
 }

 private void getTotalPageNumText() {
  getRecordNumEachPageText();
  if (recordNumEachPage == 0)
   return;
  if (totalRecord == 0) {
   totalPage = 0;
   totalPageNumText.setText(String.valueOf(0));
   return;
  }
  if (totalRecord % recordNumEachPage == 0) {//java中分頁常用到的計算公式
   totalPage = totalRecord / recordNumEachPage;
  } else {
   totalPage = totalRecord / recordNumEachPage + 1;
  }
  totalPageNumText.setText(String.valueOf(totalPage));
 }

 public void pageDown() {
  if (outOfEachPageRange()) {
   AlertDialog.Builder dialog = new AlertDialog.Builder(
     contextActivity);
   dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!")
     .setPositiveButton("確認", null).show();
   return;
  }
  if (currentPage != totalPage) {
   setCurrentPage(++currentPage);
   getTotalPageNumText();
   query(recordNumEachPage * (currentPage – 1) + 1, recordNumEachPage
     * currentPage);
  }
 }

 public void pageUp() {
  if (outOfEachPageRange()) {
   AlertDialog.Builder dialog = new AlertDialog.Builder(
     contextActivity);
   dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!")
     .setPositiveButton("確認", null).show();
   return;
  }
  if (currentPage != 1 && currentPage != 0) {
   setCurrentPage(–currentPage);
   getTotalPageNumText();
   query(recordNumEachPage * (currentPage – 1) + 1, recordNumEachPage
     * currentPage);
  }
 }

 public void firstPage() {
  if (outOfEachPageRange()) {
   AlertDialog.Builder dialog = new AlertDialog.Builder(
     contextActivity);
   dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!")
     .setPositiveButton("確認", null).show();
   return;
  }
  getTotalPageNumText();
  if (totalPage > 1) {
   setCurrentPage(1);
   query(1, recordNumEachPage);
  }
 }

 public void lastPage() {
  if (outOfEachPageRange()) {
   AlertDialog.Builder dialog = new AlertDialog.Builder(
     contextActivity);
   dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!")
     .setPositiveButton("確認", null).show();
   return;
  }
  getTotalPageNumText();
  if (totalPage != 1 && totalPage != 0) {
   setCurrentPage(totalPage);
   query(recordNumEachPage * (totalPage – 1) + 1, totalRecord);
  }
 }

 public void toPage() {
  if (outOfEachPageRange()) {
   AlertDialog.Builder dialog = new AlertDialog.Builder(
     contextActivity);
   dialog.setTitle("提示:").setMessage("每頁顯示條數在1~20之間!")
     .setPositiveButton("確認", null).show();
   return;
  }
  try {
   currentPage = Integer
     .parseInt(currentPageText.getText().toString());
  } catch (NumberFormatException e) {
   Log.e("NumberFormatException", e.getMessage());
   return;
  }
  getTotalPageNumText();
  query(recordNumEachPage * (currentPage – 1) + 1, recordNumEachPage
    * currentPage);
  currentPageText.setText(String.valueOf(currentPage));
 }

 public List<List<String>> query(int fromRecordNum, int toRecordNum) {
  return query(methodName, params, fromRecordNumField, toRecordNumField,
    fromRecordNum, toRecordNum);
 }

 private List<List<String>> query(String methodName,
   Map<String, Object> params, String fromRecordNumField,
   String toRecordNumField, int fromRecordNum, int toRecordNum) {
  params.put(fromRecordNumField, fromRecordNum);
  params.put(toRecordNumField, toRecordNum);

  return query(methodName, params);
 }

 public List<Map<String, Object>> getWholeResult() {
  return wholeresult;
 }

 public List<Map<String, Object>> getResult() {
  return wholeresult;
 }

 public List<Boolean> getCheckBoxState() {
  return dataTableAdapter.getCheckBoxState();
 }

 public List<List<String>> query(String methodName,
   Map<String, Object> params) {//此方法要重點註意,因為這裡是根據webservice查詢到的數據,所以要傳遞來方法和參數
  SoapObject result = null;

  if (methodName == null) {
   if (bSetTitleValue == false) {//下面是實現listview的標題顯示
    bSetTitleValue = true;
    myListViewTitle listViewTitle = new myListViewTitle(
      contextActivity);
    if (this.columnWidths != null) {
     listViewTitle.setTitleCellWidth(this.columnWidths);
    }
    List<String> headerList = Arrays.asList(contextActivity
      .getResources().getStringArray(headerId));
    listViewTitle.setTitleCellValue(headerList);
   }
   return null;
  }

  try {
   result = WSUtil.getSoapObjectByCallingWS(//這裡是android調用webservice的典型方法
     WebServiceConfig.NAMESPACE, methodName, params,
     WebServiceConfig.wsdl);
  } catch (Exception e) {
   new AlertDialog.Builder(contextActivity)
     .setTitle(R.string.message_title)
     .setMessage(R.string.connection_error)
     .setPositiveButton(R.string.OK_text, null).show();
   Log.e("Exception", e.getMessage());
  }

  if (result == null) {//如果從webservice得到的結果為null,那我們就找到listview,並賦空值,將分頁的顯示值設為0
   ListView list = (ListView) contextActivity.findViewById(R.id.list);
   list.setAdapter(null);
   setTotalRecord(0);
   this.setCurrentPage(0);
   return null;
  }

  SoapObject dataSet = WSObjectUtil.getDataSetObject(result);//如果從webservice得到的結果不為空,則轉化成dataSet    [java]
if (dataSet == null) {//如果dataSet為空,則顯示對話框,沒有查詢到相關數據             
               if (dataSet == null) {//如果dataSet為空,則顯示對話框,沒有查詢到相關數據   [java]
                            new AlertDialog.Builder(contextActivity) 
            .setTitle(R.string.message_title).setMessage("沒有查詢到相關數據!") 
            .setPositiveButton(R.string.OK_text, null); 
 
    return null; 

                              new AlertDialog.Builder(contextActivity)
     .setTitle(R.string.message_title).setMessage("沒有查詢到相關數據!")
     .setPositiveButton(R.string.OK_text, null);

   return null;
  }[java]
// 否則,就取得列名,並將取得的dataset轉化成list型的數據,最後將數據顯示在listview,並通過rows返回數據     
// 否則,就取得列名,並將取得的dataset轉化成list型的數據,最後將數據顯示在listview,並通過rows返回數據 [java]
    List<String> columnNameList = Arrays.asList(contextActivity 
            .getResources().getStringArray(headerNameId)); 
    WSObjectListUtil wsObjectListUtil = new WSObjectListUtil(); 
    if (contentTableName != null) { 
        rows = wsObjectListUtil.getTableValueList(dataSet, 
                contentTableName, columnNameList); 
    } else { 
        rows = wsObjectListUtil.getTableValueList(dataSet, columnNameList); 
    } 
    if (wholeresult != null) { 
        wholeresult.clear(); 
    } 
    WSObjectMapUtil wsObjectMapUtil = new WSObjectMapUtil(); 
    if (contentTableName != null) { 
        wholeresult = wsObjectMapUtil.getRowMapList(contentTableName, 
                dataSet); 
    } else { 
        wholeresult = WSObjectMapUtil.getRowMapList(dataSet); 
    } 
    SoapObject countTable = (SoapObject) dataSet.getProperty(dataSet 
            .getPropertyCount() – 1); 
    try { 
        totalRecord = Integer 
                .parseInt(countTable.getProperty(0).toString()); 
    } catch (Exception e) { 
        Log.e("Exception", e.getMessage()); 
    } 
    if (totalRecord != 0 && this.totalRecord == 0 
            && currentPageText != null) { 
        this.setCurrentPage(1); 
    } 
    setTotalRecord(totalRecord); 
 
    if (bSetTitleValue == false) { 
        bSetTitleValue = true; 
        myListViewTitle listViewTitle = new myListViewTitle(contextActivity); 
        if (this.columnWidths != null) { 
            listViewTitle.setTitleCellWidth(this.columnWidths); 
        } 
        List<String> headerList = Arrays.asList(contextActivity 
                .getResources().getStringArray(headerId)); 
        listViewTitle.setTitleCellValue(headerList); 
    } 
 
    ListView list = (ListView) contextActivity.findViewById(R.id.list); 
    dataTableAdapter = new DataTableAdapter(contextActivity, rows); 
    if (bMarkable) { 
        dataTableAdapter.setMarkable(true); 
    } 
    if (this.columnWidths != null) { 
        dataTableAdapter.setColumnWidths(this.columnWidths); 
    } 
    list.setAdapter(dataTableAdapter);//註意,關鍵點:將數據顯示在listview  
 
    return rows;//返回數據  

     List<String> columnNameList = Arrays.asList(contextActivity
    .getResources().getStringArray(headerNameId));
  WSObjectListUtil wsObjectListUtil = new WSObjectListUtil();
  if (contentTableName != null) {
   rows = wsObjectListUtil.getTableValueList(dataSet,
     contentTableName, columnNameList);
  } else {
   rows = wsObjectListUtil.getTableValueList(dataSet, columnNameList);
  }
  if (wholeresult != null) {
   wholeresult.clear();
  }
  WSObjectMapUtil wsObjectMapUtil = new WSObjectMapUtil();
  if (contentTableName != null) {
   wholeresult = wsObjectMapUtil.getRowMapList(contentTableName,
     dataSet);
  } else {
   wholeresult = WSObjectMapUtil.getRowMapList(dataSet);
  }
  SoapObject countTable = (SoapObject) dataSet.getProperty(dataSet
    .getPropertyCount() – 1);
  try {
   totalRecord = Integer
     .parseInt(countTable.getProperty(0).toString());
  } catch (Exception e) {
   Log.e("Exception", e.getMessage());
  }
  if (totalRecord != 0 && this.totalRecord == 0
    && currentPageText != null) {
   this.setCurrentPage(1);
  }
  setTotalRecord(totalRecord);

  if (bSetTitleValue == false) {
   bSetTitleValue = true;
   myListViewTitle listViewTitle = new myListViewTitle(contextActivity);
   if (this.columnWidths != null) {
    listViewTitle.setTitleCellWidth(this.columnWidths);
   }
   List<String> headerList = Arrays.asList(contextActivity
     .getResources().getStringArray(headerId));
   listViewTitle.setTitleCellValue(headerList);
  }

  ListView list = (ListView) contextActivity.findViewById(R.id.list);
  dataTableAdapter = new DataTableAdapter(contextActivity, rows);
  if (bMarkable) {
   dataTableAdapter.setMarkable(true);
  }
  if (this.columnWidths != null) {
   dataTableAdapter.setColumnWidths(this.columnWidths);
  }
  list.setAdapter(dataTableAdapter);//註意,關鍵點:將數據顯示在listview

  return rows;//返回數據
 }
}好的,這個工具類基本就實現瞭。大傢也可以自己添加一些元素完善。

摘自 jindegegesun的專欄

發佈留言