編輯:關於 Android 程式設計
Android 本身就內建了嵌入式領域常用的 SQLite,省下了自行移植安裝的功夫。SQLite 支援大部分 SQL92 標準,日常用得到的語句幾乎都能跑;除此之外,Android 還包裝了一批自訂 API,讓資料庫操作更省事。不過如果你的專案有跨平台打算,還是建議寫標準 SQL——移植起來畢竟輕鬆得多。
先看程式執行結果:

這個例子涵蓋 SQLite 的基本套路:建立資料庫、用 SQL 查詢與插入資料、關閉資料庫,最後再用 GridView 做一個分頁欄,把查到的資料按頁顯示。
分頁欄的 pagebuttons.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://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:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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>
Java 程式碼:
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 { 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;// 分頁欄的數據源 @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>>(); saPageID = new SimpleAdapter(testSQLite.this, lstPageID, R.layout.pagebuttons, 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; * 跳過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(); } }
分頁的核心就一句 SQL:select * from TABLE Limit N Offset M,跳過 M 行取 N 行。頁數則由 select count(*) 拿到的總筆數除以每頁筆數再進位而來。有興趣的讀者不妨把例子跑起來動手改改,希望對你的 Android 專案有幫助。
Android 阻止 EditText 自動取得焦點的兩個做法
進入頁面時,如果第一個控制項是 EditText,系統預設會自動把焦點給它,順帶彈出軟鍵盤,遮掉半個畫面。這個行為在大多數情況下都不是我們想要的。要阻止它,有兩個互補的做
Android 使用 Universal Image Loader 載入網路圖片並整合 ListView 互動
網路圖片載入的常見需求 在列表頁面中,網路圖片是很常見的元素。若要同時處理快取、非同步載入、記憶體管理與列表滾動時的圖片綁定,使用成熟開源庫會比自行實作更穩定。本文以 U
Android Service 的非綁定式啟動與生命週期解析
Service 若採用非綁定式(unbound)的方式啟動,建立之後就無法再與它取得聯繫——不能傳遞參數、不能取得回傳值,只能單向下指令。 如果你希望在服務啟動後仍能與
自定義 View 實戰:基於 SwipeRefreshLayout 打造上拉加載
注:本文 demo 已提交 GitHub,完整代碼地址:https://github.com/wsclwps123/UpLoadSwipeRefreshLayout,感謝