Access Context in ContentProvider
13,005
Solution 1
In your ContentProvider.onCreate method you can pass the result of getContext() to the DBHelper
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext(), db_asset);
return true;
}
Solution 2
Do you know at least a single way to get the Context from the ContentProvider?
Solution 3
Try this my friend:
SampleClass sample = new SampleClass(this.getContext());
Where this
refer to the class that extends the ContentProvider...
And .getContext()
will get the context of the class that extends the ContentProvider..
Hope this one helps..
Author by
Julian
Updated on July 22, 2022Comments
-
Julian almost 2 years
I have a ContentProvider Class and a DatabaseHelper Class (extends SQLiteOpenHelper). The ContentProvider instantiates the Helper which needs access to a Context because the constructor requires it:
public DBHelper(Context context, AssetFileDescriptor db_asset) { super(context, DB_NAME, null, 1);
Do you know at least a single way to get the Context from the ContentProvider?
Thanks :)
-
Julian almost 13 yearsthanks, I was focused on passing "this" as usual with constructors, didn't get the Idea to try something that trivial :)
-
shmoula over 10 years"focused on passing this" - you should pass application context instead of activity context to prevent memory leaks, see this post.
-
ULazdins over 7 yearsWell, Julian, it's not your fault if there is not much of a consistency in "this", "getActivity()", "getContext()", etc. use.