智汇工业-智慧工业、智能制造及工业智能、工业互联门户网站,专业的工业“互联网+”传媒

Android應用之SQLite分頁讀取

來源:網絡

點擊:2146

A+ A-

所屬頻道:新聞中心

關鍵詞: Android,SQLite分頁

        Android包含了常用于嵌入式系統的SQLite,免去了開發者自己移植安裝的功夫。SQLite 支持多數 SQL92 標準,很多常用的SQL命令都能在SQLite上面使用,除此之外Android還提供了一系列自定義的方法去簡化對SQLite數據庫的操作。不過有跨平臺需求的程序就建議使用標準的SQL語句,畢竟這樣容易在多個平臺之間移植。

    先貼出本文程序運行的結果:

     

    本文主要講解了SQLite的基本用法,如:創建數據庫,使用SQL命令查詢數據表、插入數據,關閉數據庫,以及使用GridView實現了一個分頁欄(關于GridView的用法),用于把數據分頁顯示。

    分頁欄的pagebuttons.xml的源碼如下:

    view plaincopy to clipboardprint?
    <?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_height="wrap_content" android:paddingBottom="4dip" 
        android:layout_width="fill_parent"> 
        <TextView android:layout_width="wrap_content" 
            android:layout_below="@+id/ItemImage" android:layout_height="wrap_content" 
            android:text="TextView01" android:layout_centerHorizontal="true" 
            android:id="@+id/ItemText"> 
        </TextView> 
    </RelativeLayout>   
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="wrap_content" android:paddingBottom="4dip"
     android:layout_width="fill_parent">
     <TextView android:layout_width="wrap_content"
      android:layout_below="@+id/ItemImage" android:layout_height="wrap_content"
      android:text="TextView01" android:layout_centerHorizontal="true"
      android:id="@+id/ItemText">
     </TextView>
    </RelativeLayout>  

    main.xml的源碼如下:

     

    view plaincopy to clipboardprint?
    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:orientation="vertical" android:layout_width="fill_parent" 
        android:layout_height="fill_parent"> 
        <Button android:layout_height="wrap_content" 
            android:layout_width="fill_parent" android:id="@+id/btnCreateDB" 
            android:text="創建數據庫"></Button> 
        <Button android:layout_height="wrap_content" 
            android:layout_width="fill_parent" android:text="插入一串實驗數據" android:id="@+id/btnInsertRec"></Button> 
        <Button android:layout_height="wrap_content" android:id="@+id/btnClose" 
            android:text="關閉數據庫" android:layout_width="fill_parent"></Button> 
        <EditText android:text="@+id/EditText01" android:id="@+id/EditText01" 
            android:layout_width="fill_parent" android:layout_height="256dip"></EditText> 
        <GridView android:id="@+id/gridview" android:layout_width="fill_parent" 
            android:layout_height="32dip" android:numColumns="auto_fit" 
            android:columnWidth="40dip"></GridView> 
    </LinearLayout> 
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical" android:layout_width="fill_parent"
     android:layout_height="fill_parent">
     <Button android:layout_height="wrap_content"
      android:layout_width="fill_parent" android:id="@+id/btnCreateDB"
      android:text="創建數據庫"></Button>
     <Button android:layout_height="wrap_content"
      android:layout_width="fill_parent" android:text="插入一串實驗數據" android:id="@+id/btnInsertRec"></Button>
     <Button android:layout_height="wrap_content" android:id="@+id/btnClose"
      android:text="關閉數據庫" android:layout_width="fill_parent"></Button>
     <EditText android:text="@+id/EditText01" android:id="@+id/EditText01"
      android:layout_width="fill_parent" android:layout_height="256dip"></EditText>
     <GridView android:id="@+id/gridview" android:layout_width="fill_parent"
      android:layout_height="32dip" android:numColumns="auto_fit"
      android:columnWidth="40dip"></GridView>
    </LinearLayout>
     

    本文程序源碼如下:

    view plaincopy to clipboardprint?
    package com.testSQLite;    
        
    import java.util.ArrayList;    
    import java.util.HashMap;    
    import android.app.Activity;    
    import android.database.Cursor;    
    import android.database.SQLException;    
    import android.database.sqlite.SQLiteDatabase;    
    import android.os.Bundle;    
    import android.util.Log;    
    import android.view.View;    
    import android.widget.AdapterView;    
    import android.widget.AdapterView.OnItemClickListener;    
    import android.widget.Button;    
    import android.widget.EditText;    
    import android.widget.GridView;    
    import android.widget.SimpleAdapter;    
        
    public class testSQLite extends Activity {    
        /** Called when the activity is first created. */    
        Button btnCreateDB, btnInsert, btnClose;    
        EditText edtSQL;//顯示分頁數據    
        SQLiteDatabase db;    
        int id;//添加記錄時的id累加標記,必須全局    
        static final int PageSize=10;//分頁時,每頁的數據總數    
        private static final String TABLE_NAME = "stu";    
        private static final String ID = "id";    
        private static final String NAME = "name";    
            
        SimpleAdapter saPageID;// 分頁欄適配器    
        ArrayList<HashMap<String, String>> lstPageID;// 分頁欄的數據源,與PageSize和數據總數相關    
        
        @Override    
        public void onCreate(Bundle savedInstanceState) {    
            super.onCreate(savedInstanceState);    
            setContentView(R.layout.main);    
            btnCreateDB = (Button) this.findViewById(R.id.btnCreateDB);    
            btnCreateDB.setOnClickListener(new ClickEvent());    
        
            btnInsert = (Button) this.findViewById(R.id.btnInsertRec);    
            btnInsert.setOnClickListener(new ClickEvent());    
        
            btnClose = (Button) this.findViewById(R.id.btnClose);    
            btnClose.setOnClickListener(new ClickEvent());    
                
            edtSQL=(EditText)this.findViewById(R.id.EditText01);    
                
            GridView gridview = (GridView) findViewById(R.id.gridview);//分頁欄控件    
            // 生成動態數組,并且轉入數據    
            lstPageID = new ArrayList<HashMap<String, String>>();    
        
            // 生成適配器的ImageItem <====> 動態數組的元素,兩者一一對應    
            saPageID = new SimpleAdapter(testSQLite.this, // 沒什么解釋    
                    lstPageID,// 數據來源    
                    R.layout.pagebuttons,//XML實現    
                    new String[] { "ItemText" },    
                    new int[] { R.id.ItemText });    
        
            // 添加并且顯示    
            gridview.setAdapter(saPageID);    
            // 添加消息處理    
            gridview.setOnItemClickListener(new OnItemClickListener(){    
        
                @Override    
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,    
                        long arg3) {    
                    LoadPage(arg2);//根據所選分頁讀取對應的數據    
                }    
            });    
        
        }     
         


             
        class ClickEvent implements View.OnClickListener {    
        
            @Override    
            public void onClick(View v) {    
                if (v == btnCreateDB) {    
                    CreateDB();    
                } else if (v == btnInsert) {    
                    InsertRecord(16);//插入16條記錄    
                    RefreshPage();    
                }else if (v == btnClose) {    
                    db.close();    
                }    
            }    
        
        }    
            
        
        /*  
         * 讀取指定ID的分頁數據  
         * SQL:Select * From TABLE_NAME Limit 9 Offset 10;  
         * 表示從TABLE_NAME表獲取數據,跳過10行,取9行  
         */    
        void LoadPage(int pageID)    
        {    
            String sql= "select * from " + TABLE_NAME +     
            " Limit "+String.valueOf(PageSize)+ " Offset " +String.valueOf(pageID*PageSize);    
            Cursor rec = db.rawQuery(sql, null);    
        
            setTitle("當前分頁的數據總數:"+String.valueOf(rec.getCount()));    
                
            // 取得字段名稱    
            String title = "";    
            int colCount = rec.getColumnCount();    
            for (int i = 0; i < colCount; i++)    
                title = title + rec.getColumnName(i) + "     ";    
        
                
            // 列舉出所有數據    
            String content="";    
            int recCount=rec.getCount();    
            for (int i = 0; i < recCount; i++) {//定位到一條數據    
                rec.moveToPosition(i);    
                for(int ii=0;ii<colCount;ii++)//定位到一條數據中的每個字段    
                {    
                    content=content+rec.getString(ii)+"     ";    
                }    
                content=content+"\r\n";    
            }    
                
            edtSQL.setText(title+"\r\n"+content);//顯示出來    
            rec.close();    
        }    
            
        /*  
         * 在內存創建數據庫和數據表  
         */    
        void CreateDB() {    
            // 在內存創建數據庫    
            db = SQLiteDatabase.create(null);    
            Log.e("DB Path", db.getPath());    
            String amount = String.valueOf(databaseList().length);    
            Log.e("DB amount", amount);    
            // 創建數據表    
            String sql = "CREATE TABLE " + TABLE_NAME + " (" + ID    
                    + " text not null, " + NAME + " text not null " + ");";    
            try {    
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);    
                db.execSQL(sql);    
            } catch (SQLException e) {}    
        }    
        
        /*  
         * 插入N條數據  
         */    
        void InsertRecord(int n) {    
            int total = id + n;    
            for (; id < total; id++) {    
                String sql = "insert into " + TABLE_NAME + " (" + ID + ", " + NAME    
                        + ") values(''''''''" + String.valueOf(id) + "'''''''', ''''''''test'''''''');";    
                try {    
                    db.execSQL(sql);    
                } catch (SQLException e) {    
                }    
            }    
        }    
        
        /*  
         * 插入之后刷新分頁  
         */    
        void RefreshPage()    
        {    
            String sql = "select count(*) from " + TABLE_NAME;    
            Cursor rec = db.rawQuery(sql, null);    
            rec.moveToLast();    
            long recSize=rec.getLong(0);//取得總數    
            rec.close();    
            int pageNum=(int)(recSize/PageSize) + 1;//取得分頁數    
                
            lstPageID.clear();    
            for (int i = 0; i < pageNum; i++) {    
                HashMap<String, String> map = new HashMap<String, String>();    
                map.put("ItemText", "No." + String.valueOf(i));  
        
                lstPageID.add(map);    
            }    
            saPageID.notifyDataSetChanged();    
        }    
    }   

    (審核編輯: 智匯小新)

    聲明:除特別說明之外,新聞內容及圖片均來自網絡及各大主流媒體。版權歸原作者所有。如認為內容侵權,請聯系我們刪除。

    主站蜘蛛池模板: 上海物业管理_写字楼物业管理_厂房物业管理_上海企福物业管理有限公司 | 系统门窗加盟_门窗十大品牌_欧享门窗官网 | 呼吸家官网|肺功能检测仪生产厂家|国产肺功能仪知名品牌|肺功能检测仪|肺功能测试仪|婴幼儿肺功能仪|弥散残气肺功能仪|肺功能测试系统|广州红象医疗科技有限公司|便携式肺功能仪|大肺功能仪|呼吸康复一体机|儿童肺功能仪|肺活量计|医用简易肺功能仪|呼吸康复系统|肺功能仪|弥散肺功能仪(大肺)|便携式肺功能检测仪|肺康复|呼吸肌力测定肺功能仪|肺功能测定仪|呼吸神经肌肉刺激仪|便携式肺功能 | 铝合金线棒生产厂家-提供第三代精益管,防静电工作台定制与批发-宁波杰艾逖仓储设备有限公司 | 湖北聚力汽车技术股份有限公司 | 熊猫家装-装修公司,上海装修、室内设计、家装、别墅装修、办公室装修、全屋定制就上熊猫家装 | 凿岩机|操车设备|爬车机|三环链|伞钻|伞型钻机|中心回转抓岩机|往复式给煤机|滚轮罐耳|吊桶|钩头-济宁卓力工矿设备有限公司 | 双层恒温培养箱|智能振荡培养箱-常州市仪都百科 | 河北徐工鲲鹏工程机械有限公司无锡分公司 | 华帝衣柜定制_全屋家具定制_橱柜定制-华帝家居 | 清洁度检测_手动颗粒萃取设备_自动颗粒萃取设备 - 厦门迈纳光学技术有限公司 | 塑木地板-木塑地板厂家「云南昆明楚雄曲靖玉溪塑木地板」云南云冶中信塑木新型材料有限公司 | 宁波允泰仪器有限公司-硬度计、拉力试验机、盐雾试验箱、影像测量仪、气动量仪 | 欧艺宝盾科技(北京)有限责任公司_北京旋转门厂家_转门维修_高端商务门控定制 - | 真空上料机_加料机_天津自动上料机_投料站_包装机加料_吸料机_粉体称重-天津市飞云粉体设备有限公司 | 汽车检具标准件_汽车检具配件_昆山宏易腾达模具五金有限公司 | 排污管道疏通_长沙消防管道/暗管网漏水检测维修_长沙雨水管道疏通就找湖南鸿磊环保工程有限公司 排水PVC管-PVC排污管-给水PVC管-电线PVC管-米阳建材pvc管厂 | 湖南净声源环保科技有限公司是一家专业从事噪声治理和建筑声学设计生态环境综合治理服务的企业,专业从事株洲电梯隔音治理,湘潭中央空调降噪处理,衡阳邵阳冷却塔噪音治理,岳阳常德大型风机噪声隔音降噪,张家界空压机噪声治理,益阳配电房变压器噪声治理,专业郴州永州工厂企业车间噪声治理,怀化娄底专业机械设备减振降治理,武汉噪音治理隔音降噪公司,孝感噪音治理,立式球磨机的噪声控制,专业隔音降噪公司,、以及各类机械动力设备减振降噪噪声治理的公司,同时为客户提供咨询与解决方案 | 艺考培训-中影人教育 【官网】-中国艺考教育的引航者 | 新硕考研_新硕寄宿考研-升学路上的规划师【官网】 | 武汉防雷检测_防雷工程设计施工_防雷设备材料_湖北普天科技有限公司 | 蒸汽孔板流量计-法兰式孔板流量计-一体化标准孔板流量计-金湖中原仪表有限公司 | 粘土耐火砖,低气孔耐火砖-山东耐火材料| 实验室装修设计-实验室工程建设-实验室实验台通风柜-瑞斯达实验室系统设备(苏州)有限公司 | 连云港机械手厂家_全自动焊接机械手_刀轴焊接机_智能轴类焊接机_连云港建博自动化设备有限公司 | 天力普电力科技有限公司 | 蒸汽孔板流量计-法兰式孔板流量计-一体化标准孔板流量计-金湖中原仪表有限公司 | 山东临沂春鑫新能源科技有限公司|官网|生物质颗粒锅炉|燃气锅炉|水源热泵 | 水热反应釜厂家_水热反应釜价格_水热合成反应釜批发-仪贝尔仪器 - 水热釜,水热反应釜,水热反应釜厂家,水热反应釜价格,水热反应釜型号,水热反应釜内衬,水热反应釜25ml,水热反应釜50ml,水热反应釜100ml,水热合成反应釜 | 气胀轴丨安全夹头丨电磁制动器丨纠偏系统丨磁粉离合器丨张力控制器厂家- 东莞天机通信科技有限公司 | 温州网络公司_网站建设_网络营销策划_阿里淘宝店铺服务-温州聚欣网络科技有限公司 | 塑胶跑道厂家_河北小区健身器材_悬浮地板-河北达创体育器材有限公司 | 热泵烘干机_食品烘干机_水果烘干机_蔬菜烘干机_河南蓝天机械制造有限公司 | 欧美日韩人妻精品一区二区三区_欧美成人精品欧美一级乱黄_亚洲欧美日韩高清一区二区三区_国产一级做a爰片久久毛片_日韩一级视频在线观看播放_精品一区二区三区免费毛片爱_完整观看高清秒播国内外精品资源 | 西安真石漆_无机涂料厂家_无机涂料多少钱一个平方—陕西秦森环保科技有限公司 | 天津成考网-天津成人高考网 | 西安西雷脉冲功率技术有限公司-高压调制器/加速器与脉冲功率系统的研发/生产/应用推广/高压脉冲电源的应用研究/设计/生产和销售/高功率脉冲器件/材料与仪器设备的研发/生产和销售/高电压/大电流/强磁场环境的模拟及测试服务/会议会展服务/货物及进出口的业务/脉冲功率技术领域类的技术转让 | 室内通风系统,新风系统专卖,建筑通风系统专卖_绿岛风官网 | 棕色土壤采样瓶,棕色小口水样采样瓶-上海迈隆科技有限公司 | 郑州长城冶金设备有限公司 | 爬架网@建筑爬架网@冲孔建筑爬架网片@工地冲孔建筑爬架网片@工地冲孔建筑爬架网片厂家@工地冲孔建筑爬架网片生产厂家-安平县诺德金属制品有限公司 |