0

换句话说。我想在片段中创建可编辑的文本字段,在关闭或停止应用程序后将被保存。但是return notatki;我已经有了这个:

public class DetailFragment2 extends Fragment {

    private EditText notatki;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("Test", "hello");


    }     
    @SuppressLint("SimpleDateFormat")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.details2, parent, false);
        EditText notatki = (EditText) view.findViewById(R.id.editText1);
        SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
        notatki.setText(settings.getString("value", ""));
        return notatki;
    }  
    @Override
    public void onStop( ){
        super.onStop();
        if(notatki.getText() != null) {
            SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("value", notatki.getText().toString());
            editor.commit();
        }
    }
}

当我改变return notatki;return view;直到应用程序停止时,当我想保存editText的内容但它没有保存任何东西时。

4

1 回答 1

1

可能您在以下位置将您的 EditText 设置为 null notatki

notatki.setText(settings.getString("value", "raz dwa trzy"));

因此,您有一个 NPE onStop()

notatki.getText().toString()

要解决此问题,请将您的 onStop() 方法更改为:

public void onStop( ){
    super.onStop();
    if(notatki.getText() != null) {
        SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("value", notatki.getText().toString());
        editor.commit();
    }
}
于 2013-11-12T23:35:39.090 回答