如何在无法从 getApplicationContext() 获取上下文的情况下初始化上下文?

Nav*_*aur 1 android android-context

我想访问一个扩展 SQLiteOpenHelper 的类以从 java 类获取数据库的上下文。我需要传递应用程序上下文才能获得它,但无权访问 getApplicationContext()。

如何在非活动的 java 类中获取应用程序上下文?

nbo*_*ans 5

我建议您创建一个具有 Context 类型参数的构造函数。

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

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

    //More code
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的活动中,您可以这样做:

MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this);
Run Code Online (Sandbox Code Playgroud)

在你的片段中,你可以这样做:

MySQLiteOpenHelper helper = new MySQLiteOpenHelper(getActivity().getApplicationContext()); //getActivity() would work too, Activity (indirectly) extends Context.
Run Code Online (Sandbox Code Playgroud)