Android小记-SQLiteOpenHelper正确使用避免leak

本文详细介绍了在Android开发中如何通过单例模式确保SQLite数据库实例的唯一性,避免了实例泄漏的问题。同时,提供了一个检查数据库存在的方法,并强调了使用应用程序上下文的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发中我们经常会使用到SQLite,Android提供了一个叫SQLiteOpenHelper的帮助类,但在使用的时候,如果不谨慎,经常会出现泄漏问题。建议采用单例确保database实例只有一个。

public class DatabaseHelper extends SQLiteOpenHelper { 

  private static DatabaseHelper sInstance;

  private static final String DATABASE_NAME = "database_name";
  private static final String DATABASE_TABLE = "table_name";
  private static final int DATABASE_VERSION = 1;

  public static synchronized DatabaseHelper getInstance(Context context) {

    // Use the application context, which will ensure that you 
    // don't accidentally leak an Activity's context.
    // See this article for more information: http://bit.ly/6LRzfx
    if (sInstance == null) {
      sInstance = new DatabaseHelper(context.getApplicationContext());
    }
    return sInstance;
  }

  /**
   * Constructor should be private to prevent direct instantiation.
   * make call to static method "getInstance()" instead.
   */
  private DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
}

// 下面方法用于校验某个database
private static boolean checkDatabase() {
    SQLiteDatabase checkDB = null;

    try {
        String myPath = "YourDatabasePath";
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        checkDB.close();

    } catch (Exception ex) {

    }

    return checkDB != null ? true : false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值