SoFunction
Updated on 2025-03-11

Detailed explanation of the encapsulation usage of SQLiteOpenHelper in android

There are basically three types of data storage commonly used in Android: sqlite, SharedPreferences, file storage. Among them, SQLite is used more for object storage, because it can be added, deleted, modified and checked. This article mainly explains the encapsulation and use of SQLiteOpenHelper, and the code is referenced from/iMeiji/Toutiao

Specific use

The main methods include creating databases and upgrades to the database.

Constructor: contains three parameters, context, name, factory, version

onCreate: mainly creates three forms

getDatabase: Here you can actually get two databases, namely getWritableDatabase and getReadableDatabase. The difference between these two is not particularly big, and both have read and write permissions to the database.

The instance obtained by getWritableDatabase opens the database in a read-write manner. If the opened database disk is full, it can only read but not write at this time. When the instance of getWritableDatabase is called, an error (exception) will occur (exception)

The instance obtained by getReadableDatabase is to call getWritableDatabase to open the database in a read-write manner. If the database disk is full, the return opening failure is now possible. Then use the getReadableDatabase instance to open the database in a read-only manner.

onUpgrade: mainly used for database upgrade, here

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,  factory, int version) {
    super(context, name, factory, version);
  }

  private static synchronized DatabaseHelper getInstance() {
    if (instance == null) {
      instance = new DatabaseHelper(, 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) {
      ();
    }
  }

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

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
      case 1:
        (MediaChannelTable.CREATE_TABLE);
        break;
      case 2:
        (CLEAR_TABLE_DATA + );//Delete the data in the table        break;
      case 3:
        ContentValues values = new ContentValues();
        (, "");
        (, "recommend");
        (NewsChannelTable.IS_ENABLE, 0);
        (, 46);
        (, null, values);// Create a new table        break;
      case 4:
        (SearchHistoryTable.CREATE_TABLE);
        break;
    }
  }
}

Encapsulation of table operations

addInitData adds initialization data

add insert into table

query specific data

public class NewsChannelDao {

  private SQLiteDatabase db;

  public NewsChannelDao() {
     = ();
  }

  public void addInitData() {
    String categoryId[] = ().getStringArray(.mobile_news_id);
    String categoryName[] = ().getStringArray(.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 < ; 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();
    (, channelId);
    (, channelName);
    (NewsChannelTable.IS_ENABLE, isEnable);
    (, position);
    long result = (, null, values);
    return result != -1;
  }

  public List<NewsChannelBean> query(int isEnable) {
    Cursor cursor = (, null, NewsChannelTable.IS_ENABLE + "=?",
        new String[]{isEnable + ""}, null, null, null);
    List<NewsChannelBean> list = new ArrayList<>();
    while (()) {
      NewsChannelBean bean = new NewsChannelBean();
      ((NewsChannelTable.ID_ID));
      ((NewsChannelTable.ID_NAME));
      ((NewsChannelTable.ID_ISENABLE));
      ((NewsChannelTable.ID_POSITION));
      (bean);
    }
    ();
    return list;
  }

  public List<NewsChannelBean> queryAll() {
    Cursor cursor = (, null, null, null, null, null, null);
    List<NewsChannelBean> list = new ArrayList<>();
    while (()) {
      NewsChannelBean bean = new NewsChannelBean();
      ((NewsChannelTable.ID_ID));
      ((NewsChannelTable.ID_NAME));
      ((NewsChannelTable.ID_ISENABLE));
      ((NewsChannelTable.ID_POSITION));
      (bean);
    }
    ();
    return list;
  }

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

  public boolean removeAll() {
    int result = (, null, null);
    return result != -1;
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.