0

In my preferences page I would like to delete all information stored in the database at any given time.

How would I put an onclick event when the preference is clicked on? The onClick should result in calling the delete method from my sqlite database. I have tried looking on the internet but nothing works for me. This is not a duplicate because, I have tried that already and it does not work as it is depreciated and there are no other answers with a call back to java

Can you please show me the code I would use because I do not understand what to do?

preferences.xml (for onClick)

<Preference android:title="@string/delete_all_expense"
    android:summary="@string/delete_all_expense_detail"
    android:key="delete_all_expense"
    />

PreferenceActivity.java

import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.AppCompatActivity;

public class PreferencesActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }



    public static class MyPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }

}

Delete method form DatabaseHelper (If you need it)

public void deleteAllExpense(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME,null,null);
    db.execSQL("delete from "+ TABLE_NAME);
    db.execSQL("TRUNCATE table" + TABLE_NAME);
    db.close();
}

1 Answers1

0

If this is not working for you, you can implement your own Preference like this:

public class CustomPreference extends Preference implements Preference.OnPreferenceClickListener {

    public CustomPreference(Context context, AttributeSet attrs) {
        setOnPreferenceClickListener(this)
    }


    public boolean onPreferenceClick(Preference pref) {
        //delete your data
        return true
    }
}

adding it to your .xml layout with:

<your.package.name.CustomPreference
    etc.../>
Hugou
  • 86
  • 5