开发者

SQLiteOpenHelper static methods best practice

开发者 https://www.devze.com 2023-03-15 03:14 出处:网络
I have a class extending SQLiteOpenHelper to manage my database stuff.I find it rather tedious to be writing code like this to use my database(DBHelper is the SQLiteOpenHelper object):

I have a class extending SQLiteOpenHelper to manage my database stuff. I find it rather tedious to be writing code like this to use my database(DBHelper is the SQLiteOpenHelper object):

DBHelper dbHelper = new DBHelper(context);
FeedResponse feedResponse = dbHelper.getFeedResponse(...);
dbHelper.close();

Is there anyth开发者_JAVA技巧ing wrong with replacing the above code with a static method and using it like this? Where might I run into trouble when implementing my database access like this?

FeedResponse feedResponse = DBHelper.getFeedResponse(context, ...);

public static FeedResponse getFeedResponse(Context context, ...) {
    DBHelper dbHelper = new DBHelper(context);
    FeedResponse feedResponse = dbHelper.getFeedResponse(...);
    dbHelper.close();
    return feedResponse;
}

public FeedResponse getFeedResponse(...) {
    //returns data from database
}

Doing this really cuts down on always creating(typing out) a new instance of DBHelper and also closes it without a fuss. It's all taken care of behind the scenes.


Your solution should work, but isn't optimal as you'll create a new DBHelper object for each database query. And the creation of an object is a expensive operation. It would be better if you reuse the DBHelper object.


Also you may have troubles using your DBHelper from multiple threads.

0

精彩评论

暂无评论...
验证码 换一张
取 消