溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

android 中 SQLiteOpenHelper的封裝使用詳解

發(fā)布時(shí)間:2020-09-11 17:07:02 來源:腳本之家 閱讀:138 作者:上官若楓 欄目:移動(dòng)開發(fā)

在android中常用存儲(chǔ)數(shù)據(jù)的基本就三種,sqlite,SharedPreferences,文件存儲(chǔ),其中針對(duì)于對(duì)象存儲(chǔ),使用sqlite比較多,因?yàn)榭梢詫?duì)其進(jìn)行增刪改查。本文主要講解SQLiteOpenHelper的封裝使用,代碼引用自https://github.com/iMeiji/Toutiao

具體使用

主要方法包括創(chuàng)建數(shù)據(jù)庫(kù)和數(shù)據(jù)庫(kù)的升級(jí)。

構(gòu)造函數(shù):包含三個(gè)參數(shù),context,name,factory,version

onCreate:主要?jiǎng)?chuàng)建了三張表單

getDatabase:這里其實(shí)可以獲取兩個(gè)數(shù)據(jù)庫(kù),分別是getWritableDatabase與getReadableDatabase,這兩者的區(qū)別不是特別大,都具有對(duì)數(shù)據(jù)庫(kù)的讀寫 權(quán)限。

getWritableDatabase取得的實(shí)例是以讀寫的方式打開數(shù)據(jù)庫(kù),如果打開的數(shù)據(jù)庫(kù)磁盤滿了,此時(shí)只能讀不能寫,此時(shí)調(diào)用了getWritableDatabase的實(shí)例,那么將會(huì)發(fā)生錯(cuò)誤(異常)

getReadableDatabase取得的實(shí)例是先調(diào)用getWritableDatabase以讀寫的方式打開數(shù)據(jù)庫(kù),如果數(shù)據(jù)庫(kù)的磁盤滿了,此時(shí)返回打開失敗,繼而用getReadableDatabase的實(shí)例以只讀的方式去打開數(shù)據(jù)庫(kù)

onUpgrade:主要用于數(shù)據(jù)庫(kù)的升級(jí),這里面

public class DatabaseHelper extends SQLiteOpenHelper {

  private static final String DB_NAME = "Toutiao";
  private static final int DB_VERSION = 5;
  private static final String CLEAR_TABLE_DATA = "delete from ";
  private static final String DROP_TABLE = "drop table if exists ";
  private static DatabaseHelper instance = null;
  private static SQLiteDatabase db = null;

  private DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
  }

  private static synchronized DatabaseHelper getInstance() {
    if (instance == null) {
      instance = new DatabaseHelper(InitApp.AppContext, DB_NAME, null, DB_VERSION);
    }
    return instance;
  }

  public static synchronized SQLiteDatabase getDatabase() {
    if (db == null) {
      db = getInstance().getWritableDatabase();
    }
    return db;
  }

  public static synchronized void closeDatabase() {
    if (db != null) {
      db.close();
    }
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL(NewsChannelTable.CREATE_TABLE);
    db.execSQL(MediaChannelTable.CREATE_TABLE);
    db.execSQL(SearchHistoryTable.CREATE_TABLE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
      case 1:
        db.execSQL(MediaChannelTable.CREATE_TABLE);
        break;
      case 2:
        db.execSQL(CLEAR_TABLE_DATA + NewsChannelTable.TABLENAME);//刪除表中的數(shù)據(jù)
        break;
      case 3:
        ContentValues values = new ContentValues();
        values.put(NewsChannelTable.ID, "");
        values.put(NewsChannelTable.NAME, "推薦");
        values.put(NewsChannelTable.IS_ENABLE, 0);
        values.put(NewsChannelTable.POSITION, 46);
        db.insert(NewsChannelTable.TABLENAME, null, values);//新建表
        break;
      case 4:
        db.execSQL(SearchHistoryTable.CREATE_TABLE);
        break;
    }
  }
}

表操作的封裝

addInitData添加初始化數(shù)據(jù)

add插入到表中

query查詢特定數(shù)據(jù)

public class NewsChannelDao {

  private SQLiteDatabase db;

  public NewsChannelDao() {
    this.db = DatabaseHelper.getDatabase();
  }

  public void addInitData() {
    String categoryId[] = InitApp.AppContext.getResources().getStringArray(R.array.mobile_news_id);
    String categoryName[] = InitApp.AppContext.getResources().getStringArray(R.array.mobile_news_name);
    for (int i = 0; i < 8; i++) {
      add(categoryId[i], categoryName[i], Constant.NEWS_CHANNEL_ENABLE, i);
    }
    for (int i = 8; i < categoryId.length; i++) {
      add(categoryId[i], categoryName[i], Constant.NEWS_CHANNEL_DISABLE, i);
    }
  }

  public boolean add(String channelId, String channelName, int isEnable, int position) {
    ContentValues values = new ContentValues();
    values.put(NewsChannelTable.ID, channelId);
    values.put(NewsChannelTable.NAME, channelName);
    values.put(NewsChannelTable.IS_ENABLE, isEnable);
    values.put(NewsChannelTable.POSITION, position);
    long result = db.insert(NewsChannelTable.TABLENAME, null, values);
    return result != -1;
  }

  public List<NewsChannelBean> query(int isEnable) {
    Cursor cursor = db.query(NewsChannelTable.TABLENAME, null, NewsChannelTable.IS_ENABLE + "=?",
        new String[]{isEnable + ""}, null, null, null);
    List<NewsChannelBean> list = new ArrayList<>();
    while (cursor.moveToNext()) {
      NewsChannelBean bean = new NewsChannelBean();
      bean.setChannelId(cursor.getString(NewsChannelTable.ID_ID));
      bean.setChannelName(cursor.getString(NewsChannelTable.ID_NAME));
      bean.setIsEnable(cursor.getInt(NewsChannelTable.ID_ISENABLE));
      bean.setPosition(cursor.getInt(NewsChannelTable.ID_POSITION));
      list.add(bean);
    }
    cursor.close();
    return list;
  }

  public List<NewsChannelBean> queryAll() {
    Cursor cursor = db.query(NewsChannelTable.TABLENAME, null, null, null, null, null, null);
    List<NewsChannelBean> list = new ArrayList<>();
    while (cursor.moveToNext()) {
      NewsChannelBean bean = new NewsChannelBean();
      bean.setChannelId(cursor.getString(NewsChannelTable.ID_ID));
      bean.setChannelName(cursor.getString(NewsChannelTable.ID_NAME));
      bean.setIsEnable(cursor.getInt(NewsChannelTable.ID_ISENABLE));
      bean.setPosition(cursor.getInt(NewsChannelTable.ID_POSITION));
      list.add(bean);
    }
    cursor.close();
    return list;
  }

  public void updateAll(List<NewsChannelBean> list) {
  }

  public boolean removeAll() {
    int result = db.delete(NewsChannelTable.TABLENAME, null, null);
    return result != -1;
  }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

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

AI