我是相对较新的android开发,并从ac#背景它是完全可能的,我的整个策略是错误的,但我不断收到警告由Eclipse时,我已经没有关闭数据库连接正确导致内存泄漏。垃圾收集与临时实例类
我有延伸的基础数据库类SQLiteOpenHelper
:
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
public MySQLiteOpenHelper(Context context) {
this(context, "myDb", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE MyTable (A INT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor executeSelect(String sql, String[] parameters) {
return getReadableDatabase().rawQuery(sql, parameters);
}
}
一个通用的实体:
public class MyClass {
private int a;
public void setA(int value) {
this.a = value;
}
public int getA() {
return this.a;
}
}
,基本上为MyClass
服务(虽然在现实这个范围NDS的可重用性目的的通用抽象类)
public class MyClassService {
private MySQLiteOpenHelper helper;
private Context context;
public MyClassService(Context context) {
this.context = context;
}
private MySQLiteOpenHelper getHelper() {
if (helper == null) {
helper = new MySQLiteOpenHelper(this.context);
}
return helper;
}
public void dispose() {
if (helper != null) {
helper.close();
helper = null;
}
}
public ArrayList<MyClass> getAll()
{
ArrayList<MyClass> list = new ArrayList<MyClass>();
Cursor cursor = getHelper().executeSelect("SELECT A FROM MyTable", new String[0]);
while (cursor.moveToNext()) {
MyClass item = new MyClass()
item.setA(cursor.getInt(0));
list.add(item);
}
cursor.close();
return list;
}
}
所以,我的问题是,当我用一行代码,这样从一个活动:
ArrayList<MyClass> list = new MyClassService(this).getAll();
是实例的MyClassService
立即处置,或者这可能是我的内存泄漏的来源。
我会更好地调用完整的代码来确保使用dispose方法关闭数据库吗?
MyClassService svc = new MyClassService(this);
ArrayList<MyClass> list = svc.getAll();
svc.dispose();
谢谢,你们都回答了我的问题,并建议改进。使用'context.getApplicationContext()'而不是'context'初始化MySQLiteOpenHelper是否有优势(使用'this'从一个活动传递过来)? – GarethD 2013-04-27 09:10:31
@GarethD,很高兴我能帮忙!在Android文档中,它指出传递“Activity”上下文可能会导致内存泄漏 - 如果一个活动已关闭,则会发生这种情况,但该helper保留了一个指向其上下文的指针。另一方面,应用程序的上下文与应用程序绑定,如果被终止,也会垃圾收集你的助手类。也就是说,我从来没有遇到任何传递常规上下文的问题 - 但使用Application的上下文是最安全的(主要区别是你不能使用应用上下文来修改UI)。 – Phil 2013-04-27 18:37:07