Android小记-SQLiteOpenHelper正确使用避免leak
2016-05-25 10:51
429 查看
在开发中我们经常会使用到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; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories