Question

recently I've been trying to create pseudo-AciveRecord-style db calls in my android app and came up with a bunch of class methods like User.all(Context dbContext), User.find(long id, Context dbContext), User.delete(long id, Context dbContext), etc. By pseudo-AciveRecord I mean I don't plan to make it "real ActiveRecord library" or anything like that. I just want to have an easy to understand db calls in my code and ActiveRecord style is the best for me personally. So far so good and I don't have any issues having this code for example:

    public static Cursor allAsCursor(Context dbContext) {
    DBHelper dBHelper = new DBHelper(dbContext);
    SQLiteDatabase database = dBHelper.getReadableDatabase();

    Cursor dbQueryResult = database.query(DBHelper.TABLE_NAME_USERS, null, null, null, null, null, "_id DESC");
    dbQueryResult.getCount();

    database.close();
    dBHelper.close();
    dbContext = null;


    return dbQueryResult;
}

But the thing that bothers me is that I pass activity context or something like this all the time when I make a call and I was wondering if it would be a good idea to just give my User class(which has User.find, User.all, etc.) a static variable where it would store application context for every db query? It could be done on app lunch or before the very first query request.

My thinking comes from iOS CoreData thing where you got pretty much static context manager for queries which you get all the time from shared application.

Any thoughts, suggestions, ideas?

Thanks.

Was it helpful?

Solution

Its all down to your design preference I guess, since the method is static i'm guessing all of these DB class methods are static so the class is always used in a static way? Also, are you passing in the Activity context or the application context. If you are using the application context then I would add another static method for setting the context and have a private static reference to the context.

e.g:

private static Context context;

public static void setContext(Context context){
    YourDBHelperClass.context = context;
}

Now your method can just reference this context instead of having to be passed one every time you make a transaction.

If you are passing in an activity context then I would leave it as is otherwise you risk trying to use a stale context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top