简体   繁体   中英

How to have database access in a PreferenceActivity activity?

In android I have a class derived from PreferenceActivity in order to set preferences and doing some managing stuff. One of them is to reset the database, ie to delete every item in the database and create an empty one.

Now, the database class (more specifically, SQLiteOpenHelper ) requires a Context for some reasons. But it looks like the class PreferenceActivity cannot be converted to a Context ! And so, the compiling fails.

So how to get the Context ? Or how to access the database in a different way? Or am I doing completely the wrong way?

Here is also the code:

public class UserSettingActivity extends PreferenceActivity{

    private Preference myPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        myPreference = findPreference("reset");
        myPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(UserSettingActivity.this);
                alertDialog.setMessage("Are you sure to delete the database?");
                alertDialog.setCancelable(true);
                alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        final DBAdapter db = new DBAdapter(this);
                        db.resetDatabase();

                    } });
                alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    } });
                alertDialog.show();
                return false;
            }
        });

    }

}

On a side note: The code contains deprecated code instructions. I will ask a separate question to solve this problem...

Use UserSettingActivity.this . This is possible because PreferenceActivity descends from Context see http://developer.android.com/reference/android/preference/PreferenceActivity.html

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