編輯:關於 Android 程式設計
資料庫是 Android 儲存方案的核心。在 Android 中,SQLite 相當輕量,而且執行 SQL 語句甚至比 MySQL 還快。
SQLiteDatabase 是 Android 中操作資料庫的核心類別之一,用它既能開啟資料庫,也能對資料庫進行操作。然而為了資料庫升級與使用更方便,我們常用 SQLiteOpenHelper 的子類來完成資料庫的建立與開啟。
SQLiteOpenHelper 是一個抽象類別,其中有兩個必須實作的方法:
public void onCreate(SQLiteDatabase db);// 該函數在數據庫第一次被建立時調用 public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion);// 數據庫更新升級操作
我們新建一個類別 DBHelper extends SQLiteOpenHelper:
import java.util.Random; import android.R.bool; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { // 設置數據庫默認版本 private static final int VERSON = 1; // 自定義數據庫名,可以隨便取名字 private static final String DBNAME = "mydb"; // 繼承SQLiteOpenHelper類的類必須有自己的構造函數 // 該構造函數4個參數,直接調用父類的構造函數。其中第一個參數為該類本身;第二個參數為數據庫的名字; public DBHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } // 該構造函數有3個參數,因為它把上面函數的第3個參數固定為null了 public DBHelper(Context context, String name, int verson) { this(context, name, null, verson); } // 該構造函數只有2個參數,在上面函數 的基礎上將版本號固定了 public DBHelper(Context context, String name) { this(context, name, VERSON); } // 該構造函數只有1個參數,固定默認數據庫,在這裡我們實現增刪改查為了方便,就用它了 public DBHelper(Context context) { this(context, DBNAME, null, VERSON); } // 該函數在數據庫第一次被建立時調用 public void onCreate(SQLiteDatabase db) { System.out.println("create a sqlite database"); //建表語句(注意:因為在綁定數據時,Cursor對象返回的記錄集中必須包含一個"_id"字段,否則無法完成數據綁定 String sql = "CREATE TABLE [test]("+ "[_id] AUTOINC,"+ "[name] varchar(20),"+ "[age] varchar(20),"+ "PRIMARY KEY ([_id]))"; db.execSQL(sql); //向test表中插入10條數據 for (int i = 1; i <= 10; i++) { String name = "Jepson"; name+=i; String age = "age"; age+=i; db.execSQL("insert into test(name,age) values(?,?)",new Object[]{name,age}); } } // 數據庫更新操作 public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { System.out.println("update a sqlite database"); } //自定義query方法,用以執行查詢語句,返回Cursor對象 public Cursor query(String sql,String[] args){ //調用 getReadableDatabase方法時,如果數據庫文件不存在,會調用 onCreate方法 SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(sql, args); return cursor; } }
這樣 DBHelper 類別就寫好了,我們來實現一個查詢操作。
第一步,在 activity_main.xml 加入 listview 展示控制項。
activity_main.xml
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:orientation="vertical" tools:context=".MainActivity" > <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:divider="#6b6f74" android:dividerHeight="1px" > </ListView> </LinearLayout>
第二步,新建一個 XML 版面配置檔,作為列表項使用的資源。
user_list_cell.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#FFFFFF"> <!-- 大字體TextView,用以展示 name姓名 --> <TextView android:id="@+id/tvName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Large" android:textColor="#000000" android:textSize="20dp" /> <!-- 小字體TextView,用以展示 age年齡 --> <TextView android:id="@+id/tvAge" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Small" android:textColor="#000000" android:textSize="14dp" /> </LinearLayout>
第三步,主 Activity。
import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.database.Cursor; import android.support.v4.widget.SimpleCursorAdapter; import android.view.Menu; import android.widget.Toast; public class MainActivity extends ListActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } public void initView(){ //調用只有1個參數的構造函數,實例化dbHelper DBHelper dbHelper = new DBHelper(this); //新建Cursor對象來保存query查詢方法返回的結果,查詢test表中所有記錄 Cursor cursor = dbHelper.query("select * from test", null); //創建SimpleCursorAdapter對象,5個參數, //第一個是context,就寫當前this就行 //第二個是布局文件,我這裡是自定義的布局文件user_list_cell.xml //第三個就是Cursor對象 //第四個對應就是,cursor查詢後,需要顯示出來的字段名,比如我要顯示姓名name和年齡age //第五個就是對應列表項布局中的控件ID了 SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.user_list_cell, cursor, new String[] { "name", "age" }, new int[] { R.id.tvName, R.id.tvAge }); setListAdapter(simpleCursorAdapter); Toast.makeText(this, "查詢成功", Toast.LENGTH_SHORT).show(); } }
執行一下看看,是不是查詢成功了?
操作 SQLite 資料庫時要了解到:對資料庫的增刪改查都有兩種方式,一種是前面使用的 rawQuery 直接執行 SQL 語句,另一種是使用 SQLiteDatabase 類別的相應方法來操作。下面舉一個第二種的例子,比如我們要插入 name=11、age=22 的資料:
import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.database.Cursor; import android.support.v4.widget.SimpleCursorAdapter; import android.view.Menu; import android.widget.Toast; public class MainActivity extends ListActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } public void initView(){ //執行添加操作 DBHelper dbHelper = new DBHelper(this); //獲得寫入權限getWritableDatabase SQLiteDatabase db = dbHelper.getWritableDatabase(); //新建contentvalues保存insert數據 ContentValues cv = new ContentValues(); cv.put("name", "11"); cv.put("age", "22"); db.insert("test", null, cv); Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show(); } }
執行插入成功後,再把插入語句註解掉、把查詢語句取消註解,重新啟動,會發現最後多了一個 item,代表添加成功。
另外,查詢記錄獲得的 Cursor 物件,需要使用 moveToFirst、moveToNext、moveToPosition(position) 等方法把指標移動到相應位置,才能讀取查詢結果。
import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.database.Cursor; import android.support.v4.widget.SimpleCursorAdapter; import android.view.Menu; import android.widget.Toast; public class MainActivity extends ListActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } public void initView(){ //解析Cursor對象的查詢操作 DBHelper dbHelper = new DBHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query("test", null, null, null, null, null, null, null); //定義結果字符串 String result = ""; // 判斷cursor不為空 這個很重要 if (cursor != null) { while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name"));// 獲取name列的值 String age = cursor.getString(cursor.getColumnIndex("age"));// 獲取age列的值 result += "姓名:" + name + ",年齡:" + age + "\n"; } } cursor.close(); db.close(); System.out.println(result); Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); } }
執行以後,可以發現 name 與 age 全都讀取到了,並顯示在 Toast 與 system.out 中,是不是很有意思呢?
以上就是本文的全部內容,希望對你的學習有所幫助,也希望大家多多支持本站。
Android 類加載機制淺析
Android 的類加載機制與傳統 Java 虛擬機有相似之處,也有其獨特之處。開發者在進行外掛化、動態載入或熱修復相關技術時,往往需要理解 DexClassLoader
Android 點擊展開的下拉動畫實作
下拉展開動畫的實作 下拉展開的效果在許多應用中都能看到,例如各類應用中介紹頁面的展開式說明。只要熟悉 Android 的動畫 API,製作這樣的效果並不困難。這裡使用開源
Android BroadcastReceiver 廣播接收器使用解析
BroadcastReceiver 是 Android 中負責接收廣播 Intent 的元件。系統或應用程式可以送出廣播,而接收器則負責異步接收並做出反應,例如監聽網路變
Android 基礎之 Fragment 與 Activity 互動詳解
今天繼續說明 Fragment 元件的特性,重點在於它與 Activity 的互動以及生命週期的關聯。前面提過 Fragment 依賴於 Activity,生命週期也與