Access Context in ContentProvider
Asked Answered
P

3

7

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 :)

Phillipp answered 2/8, 2011 at 22:35 Comment(0)
H
20

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;
    }
Hayrack answered 2/8, 2011 at 22:45 Comment(3)
thanks, I was focused on passing "this" as usual with constructors, didn't get the Idea to try something that trivial :)Phillipp
"focused on passing this" - you should pass application context instead of activity context to prevent memory leaks, see this post.Contention
Well, Julian, it's not your fault if there is not much of a consistency in "this", "getActivity()", "getContext()", etc. use.Incalculable
S
6

Do you know at least a single way to get the Context from the ContentProvider?

ContentProvider:getContext()

Shithead answered 2/8, 2011 at 22:48 Comment(0)
D
2

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..

Drysalter answered 28/3, 2014 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.