我尝试在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
的任何想法?
答案 0 :(得分:2)
使用getActivity()
代替getContext()
。