Naveen Mahaur
Naveen Mahaur

Reputation: 81

How to initialize context where we cannot get context from getApplicationContext()?

I want to access a class extending SQLiteOpenHelper to get the context of database from a java class. I need to pass application context to get that but don`t have access to getApplicationContext().

How can I get Application Context in java class that is not activity?

Upvotes: 1

Views: 13499

Answers (2)

nbokmans
nbokmans

Reputation: 5747

I suggest you create a constructor that has a parameter of the Context type.

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    // Variables
    private Context ctx;

    public MySQLiteOpenHelper(Context ctx) {
        this.ctx = ctx;
    }

    //More code
}

Now, in your activities, you can do this:

MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this);

And in your fragments, you can do this:

MySQLiteOpenHelper helper = new MySQLiteOpenHelper(getActivity().getApplicationContext()); //getActivity() would work too, Activity (indirectly) extends Context.

Upvotes: 5

Alex Koblov
Alex Koblov

Reputation: 36

You can create custom Application class and write method getContext().

Someting like this:

public class MyApplication extends Application {

    private static MyApplication mCurrentInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        mCurrentInstance = this;
    }


    public static MyApplication instance() {
        return mCurrentInstance;
    }

    public static Context context() {
        return mCurrentInstance.getApplicationContext();
    }
}

And add this class into manifest:

<application
        android:name=".MyApplication">

Upvotes: 0

Related Questions