简体   繁体   中英

Android open SQLite Database in Fragment

I am in a fragment in Android Studio java and want to save and read something there in a SqLite database. To save, I just use this code:

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();

But because I'm in a fragment, it marks that:

getBaseContext()

as a mistake. How can I solve this? Thanks in advance!

You can use getActivity() like this,

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

but it may invoke nullPtrException. Instead you can override this function and create like this:

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

Then use it like this,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM