android在片段中打开sqlite数据库

rn0zuynd  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(426)

我在androidstudiojava的一个片段中,想在sqlite数据库中保存和读取一些内容。为了保存,我只使用以下代码:

databaseHu = getBaseContext().openOrCreateDatabase(databaseName_Notes, MODE_PRIVATE, null);
databaseHu.execSQL("CREATE TABLE IF NOT EXISTS " + Tabel_Hu_Name + "(subject TEXT, tasks TEXT, dayofyear INT, day INT, month INT, year INT)");
databaseHu.execSQL("INSERT INTO  " + Tabel_Hu_Name + " VALUES ('" + subject.getText().toString() + "','" + tasks.getText().toString() + "','" + c.get(Calendar.DAY_OF_YEAR) + "','" + c.get(Calendar.DAY_OF_MONTH) + "','" + c.get(Calendar.MONTH) + "','" + c.get(Calendar.YEAR) + "')");
databaseHu.close();

但因为我是一个碎片,它标志着:

getBaseContext()

作为一个错误。我怎样才能解决这个问题?提前谢谢!

093gszye

093gszye1#

可以这样使用getactivity(),

databaseHu = getActivity().getBaseContext().openOrCreateDatabase(databaseName_Notes, MODE_PRIVATE, null);

但它可能会调用nullptrexception。相反,您可以重写此函数并创建如下内容:

Activity activity;
@override
public void onViewCreated(View view, Bundle savedInstanceState) {
    if(getActivity()==null){
        activity = getActivity;
    }
}

然后像这样使用,

databaseHu = activity.getBaseContext().openOrCreateDatabase(databaseName_Notes, MODE_PRIVATE, null);

相关问题