PreferenceFragment中的AlertDialog崩溃应用程序

时间:2015-11-01 18:13:33

标签: android android-fragments android-alertdialog android-context

我尝试在AlertDialog中创建PreferenceFragment,以便用户确认他/她是否要删除所有用户数据。

这是我所做的代码:

public class SettingsFragment extends PreferenceFragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle b = getArguments();
    addPreferencesFromResource(R.xml.preferences);


    Preference button = (Preference)findPreference(getString(R.string.Delete_user_info));
    button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public boolean onPreferenceClick(Preference preference) {
            //An Alertbuilder
            new AlertDialog.Builder(getContext()) //THIS LINE CRASHES THE APP
                    .setMessage("Do you really want to permanently delete your likes?\nYou will not be able to restore them!!")
                    .setCancelable(true)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            new DeleteUserInfo().execute();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    })
                    .create()
                    .show();
            return true;
        }
    });
}
}

这是LogCat中的结果:

11-01 18:58:38.501 29821-29821/com.astudio.andreas.mapstest E/AndroidRuntime: FATAL EXCEPTION: main
11-01 18:58:38.501 29821-29821/com.astudio.andreas.mapstest E/AndroidRuntime: Process: com.astudio.andreas.mapstest, PID: 29821
11-01 18:58:38.501 29821-29821/com.astudio.andreas.mapstest E/AndroidRuntime: java.lang.NoSuchMethodError: No virtual method getContext()Landroid/content/Context; in class Lcom/astudio/andreas/mapstest/SettingsFragment; or its super classes (declaration of 'com.astudio.andreas.mapstest.SettingsFragment' appears in /data/app/com.astudio.andreas.mapstest-1/base.apk)
11-01 18:58:38.501 29821-29821/com.astudio.andreas.mapstest E/AndroidRuntime:     at com.astudio.andreas.mapstest.SettingsFragment$1.onPreferenceClick(SettingsFragment.java:41)

关于如何正确引用Context的任何想法?

1 个答案:

答案 0 :(得分:2)

使用getActivity()代替getContext()