溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android中SQLite怎么使用

發(fā)布時間:2021-07-12 11:35:00 來源:億速云 閱讀:130 作者:Leah 欄目:移動開發(fā)

今天就跟大家聊聊有關Android中SQLite怎么使用,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據(jù)這篇文章可以有所收獲。

Android中SQLite 使用方法詳解

  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
     
    //打開或創(chuàng)建test.db數(shù)據(jù)庫 
    SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); 
    db.execSQL("DROP TABLE IF EXISTS person"); 
    //創(chuàng)建person表 
    db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)"); 
    Person person = new Person(); 
    person.name = "john"; 
    person.age = 30; 
    //插入數(shù)據(jù) 
    db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)", new Object[]{person.name, person.age}); 
     
    person.name = "david"; 
    person.age = 33; 
    //ContentValues以鍵值對的形式存放數(shù)據(jù) 
    ContentValues cv = new ContentValues(); 
    cv.put("name", person.name); 
    cv.put("age", person.age); 
    //插入ContentValues中的數(shù)據(jù) 
    db.insert("person", null, cv); 
     
    cv = new ContentValues(); 
    cv.put("age", 35); 
    //更新數(shù)據(jù) 
    db.update("person", cv, "name = ?", new String[]{"john"}); 
     
    Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"33"}); 
    while (c.moveToNext()) { 
      int _id = c.getInt(c.getColumnIndex("_id")); 
      String name = c.getString(c.getColumnIndex("name")); 
      int age = c.getInt(c.getColumnIndex("age")); 
      Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age); 
    } 
    c.close(); 
     
    //刪除數(shù)據(jù) 
    db.delete("person", "age < ?", new String[]{"35"}); 
     
    //關閉當前數(shù)據(jù)庫 
    db.close(); 
     
    //刪除test.db數(shù)據(jù)庫 
//   deleteDatabase("test.db"); 
  }

在執(zhí)行完上面的代碼后,系統(tǒng)就會在/data/data/[PACKAGE_NAME]/databases目錄下生成一個“test.db”的數(shù)據(jù)庫文件,如圖:

Android中SQLite怎么使用

上面的代碼中基本上囊括了大部分的數(shù)據(jù)庫操作;對于添加、更新和刪除來說,我們都可以使用

db.executeSQL(String sql); 
db.executeSQL(String sql, Object[] bindArgs);//sql語句中使用占位符,然后第二個參數(shù)是實際的參數(shù)集

除了統(tǒng)一的形式之外,他們還有各自的操作方法:

db.insert(String table, String nullColumnHack, ContentValues values); 
db.update(String table, Contentvalues values, String whereClause, String whereArgs); 
db.delete(String table, String whereClause, String whereArgs);

以上三個方法的第一個參數(shù)都是表示要操作的表名;insert中的第二個參數(shù)表示如果插入的數(shù)據(jù)每一列都為空的話,需要指定此行中某一列的名稱,系統(tǒng)將此列設置為NULL,不至于出現(xiàn)錯誤;insert中的第三個參數(shù)是ContentValues類型的變量,是鍵值對組成的Map,key代表列名,value代表該列要插入的值;update的第二個參數(shù)也很類似,只不過它是更新該字段key為最新的value值,第三個參數(shù)whereClause表示W(wǎng)HERE表達式,比如“age > ? and age < ?”等,最后的whereArgs參數(shù)是占位符的實際參數(shù)值;delete方法的參數(shù)也是一樣。

下面來說說查詢操作。查詢操作相對于上面的幾種操作要復雜些,因為我們經常要面對著各種各樣的查詢條件,所以系統(tǒng)也考慮到這種復雜性,為我們提供了較為豐富的查詢形式:

db.rawQuery(String sql, String[] selectionArgs); 
db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy); 
db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit); 
db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

上面幾種都是常用的查詢方法,第一種最為簡單,將所有的SQL語句都組織到一個字符串中,使用占位符代替實際參數(shù),selectionArgs就是占位符實際參數(shù)集;下面的幾種參數(shù)都很類似,columns表示要查詢的列所有名稱集,selection表示W(wǎng)HERE之后的條件語句,可以使用占位符,groupBy指定分組的列名,having指定分組條件,配合groupBy使用,orderBy指定排序的列名,limit指定分頁參數(shù),distinct可以指定“true”或“false”表示要不要過濾重復值。需要注意的是,selection、groupBy、having、orderBy、limit這幾個參數(shù)中不包括“WHERE”、“GROUP BY”、“HAVING”、“ORDER BY”、“LIMIT”等SQL關鍵字。

最后,他們同時返回一個Cursor對象,代表數(shù)據(jù)集的游標,有點類似于JavaSE中的ResultSet。

下面是Cursor對象的常用方法:

c.move(int offset); //以當前位置為參考,移動到指定行 
c.moveToFirst();  //移動到第一行 
c.moveToLast();   //移動到最后一行 
c.moveToPosition(int position); //移動到指定行 
c.moveToPrevious(); //移動到前一行 
c.moveToNext();   //移動到下一行 
c.isFirst();    //是否指向第一條 
c.isLast();   //是否指向最后一條 
c.isBeforeFirst(); //是否指向第一條之前 
c.isAfterLast();  //是否指向最后一條之后 
c.isNull(int columnIndex); //指定列是否為空(列基數(shù)為0) 
c.isClosed();    //游標是否已關閉 
c.getCount();    //總數(shù)據(jù)項數(shù) 
c.getPosition();  //返回當前游標所指向的行數(shù) 
c.getColumnIndex(String columnName);//返回某列名對應的列索引值 
c.getString(int columnIndex);  //返回當前行指定列的值

在上面的代碼示例中,已經用到了這幾個常用方法中的一些,關于更多的信息,大家可以參考官方文檔中的說明。
最后當我們完成了對數(shù)據(jù)庫的操作后,記得調用SQLiteDatabase的close()方法釋放數(shù)據(jù)庫連接,否則容易出現(xiàn)SQLiteException。

上面就是SQLite的基本應用,但在實際開發(fā)中,為了能夠更好的管理和維護數(shù)據(jù)庫,我們會封裝一個繼承自SQLiteOpenHelper類的數(shù)據(jù)庫操作類,然后以這個類為基礎,再封裝我們的業(yè)務邏輯方法。

下面,我們就以一個實例來講解具體的用法,我們新建一個名為db的項目,結構如下:

Android中SQLite怎么使用

其中DBHelper繼承了SQLiteOpenHelper,作為維護和管理數(shù)據(jù)庫的基類,DBManager是建立在DBHelper之上,封裝了常用的業(yè)務方法,Person是我們的person表對應的JavaBean,MainActivity就是我們顯示的界面。

下面我們先來看一下DBHelper:

package com.scott.db; 
 
import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
 
public class DBHelper extends SQLiteOpenHelper { 
 
  private static final String DATABASE_NAME = "test.db"; 
  private static final int DATABASE_VERSION = 1; 
   
  public DBHelper(Context context) { 
    //CursorFactory設置為null,使用默認值 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
  } 
 
  //數(shù)據(jù)庫第一次被創(chuàng)建時onCreate會被調用 
  @Override 
  public void onCreate(SQLiteDatabase db) { 
    db.execSQL("CREATE TABLE IF NOT EXISTS person" + 
        "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)"); 
  } 
 
  //如果DATABASE_VERSION值被改為2,系統(tǒng)發(fā)現(xiàn)現(xiàn)有數(shù)據(jù)庫版本不同,即會調用onUpgrade 
  @Override 
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("ALTER TABLE person ADD COLUMN other STRING"); 
  } 
}

正如上面所述,數(shù)據(jù)庫第一次創(chuàng)建時onCreate方法會被調用,我們可以執(zhí)行創(chuàng)建表的語句,當系統(tǒng)發(fā)現(xiàn)版本變化之后,會調用onUpgrade方法,我們可以執(zhí)行修改表結構等語句。

為了方便我們面向對象的使用數(shù)據(jù),我們建一個Person類,對應person表中的字段,如下:

package com.scott.db; 
 
public class Person { 
  public int _id; 
  public String name; 
  public int age; 
  public String info; 
   
  public Person() { 
  } 
   
  public Person(String name, int age, String info) { 
    this.name = name; 
    this.age = age; 
    this.info = info; 
  } 
}

然后,我們需要一個DBManager,來封裝我們所有的業(yè)務方法,代碼如下:

package com.scott.db; 
 
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 DBManager { 
  private DBHelper helper; 
  private SQLiteDatabase db; 
   
  public DBManager(Context context) { 
    helper = new DBHelper(context); 
    //因為getWritableDatabase內部調用了mContext.openOrCreateDatabase(mName, 0, mFactory); 
    //所以要確保context已初始化,我們可以把實例化DBManager的步驟放在Activity的onCreate里 
    db = helper.getWritableDatabase(); 
  } 
   
  /** 
   * add persons 
   * @param persons 
   */ 
  public void add(List<Person> persons) { 
    db.beginTransaction(); //開始事務 
    try { 
      for (Person person : persons) { 
        db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info}); 
      } 
      db.setTransactionSuccessful(); //設置事務成功完成 
    } finally { 
      db.endTransaction();  //結束事務 
    } 
  } 
   
  /** 
   * update person's age 
   * @param person 
   */ 
  public void updateAge(Person person) { 
    ContentValues cv = new ContentValues(); 
    cv.put("age", person.age); 
    db.update("person", cv, "name = ?", new String[]{person.name}); 
  } 
   
  /** 
   * delete old person 
   * @param person 
   */ 
  public void deleteOldPerson(Person person) { 
    db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)}); 
  } 
   
  /** 
   * query all persons, return list 
   * @return List<Person> 
   */ 
  public List<Person> query() { 
    ArrayList<Person> persons = new ArrayList<Person>(); 
    Cursor c = queryTheCursor(); 
    while (c.moveToNext()) { 
      Person person = new Person(); 
      person._id = c.getInt(c.getColumnIndex("_id")); 
      person.name = c.getString(c.getColumnIndex("name")); 
      person.age = c.getInt(c.getColumnIndex("age")); 
      person.info = c.getString(c.getColumnIndex("info")); 
      persons.add(person); 
    } 
    c.close(); 
    return persons; 
  } 
   
  /** 
   * query all persons, return cursor 
   * @return Cursor 
   */ 
  public Cursor queryTheCursor() { 
    Cursor c = db.rawQuery("SELECT * FROM person", null); 
    return c; 
  } 
   
  /** 
   * close database 
   */ 
  public void closeDB() { 
    db.close(); 
  } 
}

我們在DBManager構造方法中實例化DBHelper并獲取一個SQLiteDatabase對象,作為整個應用的數(shù)據(jù)庫實例;在添加多個Person信息時,我們采用了事務處理,確保數(shù)據(jù)完整性;最后我們提供了一個closeDB方法,釋放數(shù)據(jù)庫資源,這一個步驟在

我們整個應用關閉時執(zhí)行,這個環(huán)節(jié)容易被忘記,所以朋友們要注意。

我們獲取數(shù)據(jù)庫實例時使用了getWritableDatabase()方法,也許朋友們會有疑問,在getWritableDatabase()和getReadableDatabase()中,你為什么選擇前者作為整個應用的數(shù)據(jù)庫實例呢?在這里我想和大家著重分析一下這一點。
我們來看一下SQLiteOpenHelper中的getReadableDatabase()方法:

public synchronized SQLiteDatabase getReadableDatabase() { 
  if (mDatabase != null && mDatabase.isOpen()) { 
    // 如果發(fā)現(xiàn)mDatabase不為空并且已經打開則直接返回 
    return mDatabase; 
  } 
 
  if (mIsInitializing) { 
    // 如果正在初始化則拋出異常 
    throw new IllegalStateException("getReadableDatabase called recursively"); 
  } 
 
  // 開始實例化數(shù)據(jù)庫mDatabase 
 
  try { 
    // 注意這里是調用了getWritableDatabase()方法 
    return getWritableDatabase(); 
  } catch (SQLiteException e) { 
    if (mName == null) 
      throw e; // Can't open a temp database read-only! 
    Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e); 
  } 
 
  // 如果無法以可讀寫模式打開數(shù)據(jù)庫 則以只讀方式打開 
 
  SQLiteDatabase db = null; 
  try { 
    mIsInitializing = true; 
    String path = mContext.getDatabasePath(mName).getPath();// 獲取數(shù)據(jù)庫路徑 
    // 以只讀方式打開數(shù)據(jù)庫 
    db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY); 
    if (db.getVersion() != mNewVersion) { 
      throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to " 
          + mNewVersion + ": " + path); 
    } 
 
    onOpen(db); 
    Log.w(TAG, "Opened " + mName + " in read-only mode"); 
    mDatabase = db;// 為mDatabase指定新打開的數(shù)據(jù)庫 
    return mDatabase;// 返回打開的數(shù)據(jù)庫 
  } finally { 
    mIsInitializing = false; 
    if (db != null && db != mDatabase) 
      db.close(); 
  } 
}

在getReadableDatabase()方法中,首先判斷是否已存在數(shù)據(jù)庫實例并且是打開狀態(tài),如果是,則直接返回該實例,否則試圖獲取一個可讀寫模式的數(shù)據(jù)庫實例,如果遇到磁盤空間已滿等情況獲取失敗的話,再以只讀模式打開數(shù)據(jù)庫,獲取數(shù)據(jù)庫實例并返回,然后為mDatabase賦值為最新打開的數(shù)據(jù)庫實例。既然有可能調用到getWritableDatabase()方法,我們就要看一下了:

public synchronized SQLiteDatabase getWritableDatabase() { 
  if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) { 
    // 如果mDatabase不為空已打開并且不是只讀模式 則返回該實例 
    return mDatabase; 
  } 
 
  if (mIsInitializing) { 
    throw new IllegalStateException("getWritableDatabase called recursively"); 
  } 
 
  // If we have a read-only database open, someone could be using it 
  // (though they shouldn't), which would cause a lock to be held on 
  // the file, and our attempts to open the database read-write would 
  // fail waiting for the file lock. To prevent that, we acquire the 
  // lock on the read-only database, which shuts out other users. 
 
  boolean success = false; 
  SQLiteDatabase db = null; 
  // 如果mDatabase不為空則加鎖 阻止其他的操作 
  if (mDatabase != null) 
    mDatabase.lock(); 
  try { 
    mIsInitializing = true; 
    if (mName == null) { 
      db = SQLiteDatabase.create(null); 
    } else { 
      // 打開或創(chuàng)建數(shù)據(jù)庫 
      db = mContext.openOrCreateDatabase(mName, 0, mFactory); 
    } 
    // 獲取數(shù)據(jù)庫版本(如果剛創(chuàng)建的數(shù)據(jù)庫,版本為0) 
    int version = db.getVersion(); 
    // 比較版本(我們代碼中的版本mNewVersion為1) 
    if (version != mNewVersion) { 
      db.beginTransaction();// 開始事務 
      try { 
        if (version == 0) { 
          // 執(zhí)行我們的onCreate方法 
          onCreate(db); 
        } else { 
          // 如果我們應用升級了mNewVersion為2,而原版本為1則執(zhí)行onUpgrade方法 
          onUpgrade(db, version, mNewVersion); 
        } 
        db.setVersion(mNewVersion);// 設置最新版本 
        db.setTransactionSuccessful();// 設置事務成功 
      } finally { 
        db.endTransaction();// 結束事務 
      } 
    } 
 
    onOpen(db); 
    success = true; 
    return db;// 返回可讀寫模式的數(shù)據(jù)庫實例 
  } finally { 
    mIsInitializing = false; 
    if (success) { 
      // 打開成功 
      if (mDatabase != null) { 
        // 如果mDatabase有值則先關閉 
        try { 
          mDatabase.close(); 
        } catch (Exception e) { 
        } 
        mDatabase.unlock();// 解鎖 
      } 
      mDatabase = db;// 賦值給mDatabase 
    } else { 
      // 打開失敗的情況:解鎖、關閉 
      if (mDatabase != null) 
        mDatabase.unlock(); 
      if (db != null) 
        db.close(); 
    } 
  } 
}

大家可以看到,幾個關鍵步驟是,首先判斷mDatabase如果不為空已打開并不是只讀模式則直接返回,否則如果mDatabase不為空則加鎖,然后開始打開或創(chuàng)建數(shù)據(jù)庫,比較版本,根據(jù)版本號來調用相應的方法,為數(shù)據(jù)庫設置新版本號,最后釋放舊的不為空的mDatabase并解鎖,把新打開的數(shù)據(jù)庫實例賦予mDatabase,并返回最新實例。

看完上面的過程之后,大家或許就清楚了許多,如果不是在遇到磁盤空間已滿等情況,getReadableDatabase()一般都會返回和getWritableDatabase()一樣的數(shù)據(jù)庫實例,所以我們在DBManager構造方法中使用getWritableDatabase()獲取整個應用所使用的數(shù)據(jù)庫實例是可行的。當然如果你真的擔心這種情況會發(fā)生,那么你可以先用getWritableDatabase()獲取數(shù)據(jù)實例,如果遇到異常,再試圖用getReadableDatabase()獲取實例,當然這個時候你獲取的實例只能讀不能寫了。

最后,讓我們看一下如何使用這些數(shù)據(jù)操作方法來顯示數(shù)據(jù),下面是MainActivity.Java的布局文件和代碼:

<?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_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="add" 
    android:onClick="add"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="update" 
    android:onClick="update"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="delete" 
    android:onClick="delete"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="query" 
    android:onClick="query"/> 
  <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="queryTheCursor" 
    android:onClick="queryTheCursor"/> 
  <ListView 
    android:id="@+id/listView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/> 
</LinearLayout>
package com.scott.db; 
 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import android.app.Activity; 
import android.database.Cursor; 
import android.database.CursorWrapper; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.SimpleCursorAdapter; 
 
 
public class MainActivity extends Activity { 
   
  private DBManager mgr; 
  private ListView listView; 
   
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    listView = (ListView) findViewById(R.id.listView); 
    //初始化DBManager 
    mgr = new DBManager(this); 
  } 
   
  @Override 
  protected void onDestroy() { 
    super.onDestroy(); 
    //應用的最后一個Activity關閉時應釋放DB 
    mgr.closeDB(); 
  } 
   
  public void add(View view) { 
    ArrayList<Person> persons = new ArrayList<Person>(); 
     
    Person person1 = new Person("Ella", 22, "lively girl"); 
    Person person2 = new Person("Jenny", 22, "beautiful girl"); 
    Person person3 = new Person("Jessica", 23, "sexy girl"); 
    Person person4 = new Person("Kelly", 23, "hot baby"); 
    Person person5 = new Person("Jane", 25, "a pretty woman"); 
     
    persons.add(person1); 
    persons.add(person2); 
    persons.add(person3); 
    persons.add(person4); 
    persons.add(person5); 
     
    mgr.add(persons); 
  } 
   
  public void update(View view) { 
    Person person = new Person(); 
    person.name = "Jane"; 
    person.age = 30; 
    mgr.updateAge(person); 
  } 
   
  public void delete(View view) { 
    Person person = new Person(); 
    person.age = 30; 
    mgr.deleteOldPerson(person); 
  } 
   
  public void query(View view) { 
    List<Person> persons = mgr.query(); 
    ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); 
    for (Person person : persons) { 
      HashMap<String, String> map = new HashMap<String, String>(); 
      map.put("name", person.name); 
      map.put("info", person.age + " years old, " + person.info); 
      list.add(map); 
    } 
    SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, 
          new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2}); 
    listView.setAdapter(adapter); 
  } 
   
  public void queryTheCursor(View view) { 
    Cursor c = mgr.queryTheCursor(); 
    startManagingCursor(c); //托付給activity根據(jù)自己的生命周期去管理Cursor的生命周期 
    CursorWrapper cursorWrapper = new CursorWrapper(c) { 
      @Override 
      public String getString(int columnIndex) { 
        //將簡介前加上年齡 
        if (getColumnName(columnIndex).equals("info")) { 
          int age = getInt(getColumnIndex("age")); 
          return age + " years old, " + super.getString(columnIndex); 
        } 
        return super.getString(columnIndex); 
      } 
    }; 
    //確保查詢結果中有"_id"列 
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,  
        cursorWrapper, new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2}); 
    ListView listView = (ListView) findViewById(R.id.listView); 
    listView.setAdapter(adapter); 
  } 
}

這里需要注意的是SimpleCursorAdapter的應用,當我們使用這個適配器時,我們必須先得到一個Cursor對象,這里面有幾個問題:如何管理Cursor的生命周期,如果包裝Cursor,Cursor結果集都需要注意什么。

如果手動去管理Cursor的話會非常的麻煩,還有一定的風險,處理不當?shù)脑掃\行期間就會出現(xiàn)異常,幸好Activity為我們提供了startManagingCursor(Cursor cursor)方法,它會根據(jù)Activity的生命周期去管理當前的Cursor對象,下面是該方法的說明:

/** 
   * This method allows the activity to take care of managing the given 
   * {@link Cursor}'s lifecycle for you based on the activity's lifecycle. 
   * That is, when the activity is stopped it will automatically call 
   * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted 
   * it will call {@link Cursor#requery} for you. When the activity is 
   * destroyed, all managed Cursors will be closed automatically. 
   * 
   * @param c The Cursor to be managed. 
   * 
   * @see #managedQuery(android.net.Uri , String[], String, String[], String) 
   * @see #stopManagingCursor 
   */

文中提到,startManagingCursor方法會根據(jù)Activity的生命周期去管理當前的Cursor對象的生命周期,就是說當Activity停止時他會自動調用Cursor的deactivate方法,禁用游標,當Activity重新回到屏幕時它會調用Cursor的requery方法再次查詢,當Activity摧毀時,被管理的Cursor都會自動關閉釋放。

如何包裝Cursor:我們會使用到CursorWrapper對象去包裝我們的Cursor對象,實現(xiàn)我們需要的數(shù)據(jù)轉換工作,這個CursorWrapper實際上是實現(xiàn)了Cursor接口。我們查詢獲取到的Cursor其實是Cursor的引用,而系統(tǒng)實際返回給我們的必然是Cursor接口的一個實現(xiàn)類的對象實例,我們用CursorWrapper包裝這個實例,然后再使用SimpleCursorAdapter將結果顯示到列表上。

Cursor結果集需要注意些什么:一個最需要注意的是,在我們的結果集中必須要包含一個“_id”的列,否則SimpleCursorAdapter就會翻臉不認人,為什么一定要這樣呢?因為這源于SQLite的規(guī)范,主鍵以“_id”為標準。解決辦法有

三:第一,建表時根據(jù)規(guī)范去做;第二,查詢時用別名,例如:SELECT id AS _id FROM person;第三,在CursorWrapper里做文章:

CursorWrapper cursorWrapper = new CursorWrapper(c) { 
  @Override 
  public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { 
    if (columnName.equals("_id")) { 
      return super.getColumnIndex("id"); 
    } 
    return super.getColumnIndexOrThrow(columnName); 
  } 
};

如果試圖從CursorWrapper里獲取“_id”對應的列索引,我們就返回查詢結果里“id”對應的列索引即可。
最后我們來看一下結果如何:

Android中SQLite怎么使用

Android中SQLite怎么使用

看完上述內容,你們對Android中SQLite怎么使用有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI