在片段中保存EditText(textfield)值

时间:2013-11-12 22:33:24

标签: android android-fragments android-edittext

换句话说。我想在片段中创建可编辑的文本字段,在关闭或停止应用程序后将保存。但是有一些错误符合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的内容但它不会保存任何内容时。

1 个答案:

答案 0 :(得分:1)

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

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

因此,您在onStop()处有一个NPE:

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();
    }
}