设置屏幕的SharedPreferences

时间:2018-01-17 05:39:58

标签: android android-sharedpreferences

我正在尝试使用SharedPreferences为我的应用设置屏幕。当应用程序加载时,它会显示默认的“空白”文本,但是当我点击保存按钮时,我的应用程序崩溃了。我在这里做错了什么?

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_settings, container, false);

    Button saveButton = (Button) view.findViewById(R.id.save);
    EditText firstName = (EditText) view.findViewById(R.id.firstName);

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    firstName.setText(sharedPref.getString("firstName", "blank"));

    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("firstName", view.findViewById(R.id.firstName).toString());
            editor.commit();

        }
    });
    return view;
}

2 个答案:

答案 0 :(得分:0)

试试这个:

editor.putString("firstName", view.findViewById(R.id.firstName).getText().toString());

答案 1 :(得分:0)

尝试此更改。

替换

view.findViewById(R.id.firstName).toString()

firstName.getText().toString()