android - 自定义警报对话框中的共享首选项

标签 android sharedpreferences android-alertdialog

我想将 EditText(位于 AlertDialog)字段的值存储在 SharedPreference 中。它在 SharedPreferences.Editor editor = sp.edit(); 这行显示 NullPointerException **注意:代码在没有 SharedPreferences 的情况下工作 **

    private void myDialog() {
    // TODO Auto-generated method stub
    LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
    View view = inflater.inflate(R.layout.cus_dialog, null);
    AlertDialog.Builder ab = new AlertDialog.Builder(this);
    ab.setView(view);
    final EditText input = (EditText) view.findViewById(R.id.etValue);

    ab.setCancelable(false);
    ab.setPositiveButton("Send", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            String s = input.getText().toString();
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("A", s);
            editor.commit();
            Toast.makeText(getApplicationContext(), "" + s,
                    Toast.LENGTH_SHORT).show();
        }
    });
    ab.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.cancel();
        }
    });
    AlertDialog ad = ab.create();

    ad.show();
}

enter image description here

最佳答案

SharedPreferences preferences = PreferenceManager
                        .getDefaultSharedPreferences(acivity.this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("a", "a");
                editor.commit();

关于android - 自定义警报对话框中的共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15676802/

相关文章:

android - 从 Android 设备身份验证扫描仪获取指纹 JPEG 图像

java - 从相机或图库中选择图像

java - 从首选项设置屏幕返回时刷新 MainActivity

android - 保存在 SharedPreferences 中的用户设置在应用重新加载之间被删除或丢失

android - BroadcastReceiver 中的 SharedPreferences 似乎没有更新?

Android Childactivity getParent 问题?

java - android中显示alertdialog时如何不禁用后台交互

android - NFC 服务死机 android.os.DeadObjectException

android - Android Studio 中的 list 合并

AlertDialog 中的 Android 选项卡