我确信这是我忽略的非常基本的东西,但与我研究过的所有文章相比,我似乎做得对。
我有一个 DialogPreference,其中包含用户名和密码的编辑文本和一个将数据保存到首选项的按钮。创建后,我想查询首选项并用以前保存的要编辑的数据填充编辑文本框,否则将框留空。目前,如果不存在以前的数据,我没有任何问题,但如果数据确实存在,我的应用程序在尝试打开 DialogPreference 时崩溃。
我的 DialogPreference 代码:
public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener {
private EditText mUserbox, mPassbox;
CharSequence mPassboxdata, mUserboxdata;
private Context mContext;
private int mWhichButtonClicked;
public AccDialog(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
@Override
protected View onCreateDialogView() {
// Access default SharedPreferences
@SuppressWarnings("unused")
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
// Register listener
final OnCheckedChangeListener mShowchar_listener;
// Run the following methods onCreate
existingData();
@SuppressWarnings("unused")
LinearLayout.LayoutParams params;
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(10, 10, 10, 10);
layout.setBackgroundColor(0xFF000000);
mUserbox = new EditText(mContext);
mUserbox.setSingleLine(true);
mUserbox.setSelectAllOnFocus(true);
mPassbox = new EditText(mContext);
mPassbox.setSingleLine(true);
mPassbox.setSelectAllOnFocus(true);
layout.addView(mUserbox);
layout.addView(mPassbox);
return layout;
}
private void existingData() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
String Unamedata = pref.getString("usernamekey", "");
String Pworddata = pref.getString("passwordkey", "");
if((Unamedata.length() != 0) && (Pworddata.length() != 0)) {
mUserbox.setText(Unamedata);
mPassbox.setText(Pworddata);
}
}
}