Android小记-SQLiteOpenHelper正确使用避免leak
Posted everlastxgb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android小记-SQLiteOpenHelper正确使用避免leak相关的知识,希望对你有一定的参考价值。
在开发中我们经常会使用到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;
以上是关于Android小记-SQLiteOpenHelper正确使用避免leak的主要内容,如果未能解决你的问题,请参考以下文章