A
A
Andrew2016-09-07 16:56:52
Java
Andrew, 2016-09-07 16:56:52

Application crash with setOnClickListener?

I'm making two buttons to load the saved text and save it. in OnCreate:

etText = (EditText)findViewById(R.id.etText); //поле для ввода
    btnSave = (Button)findViewById(R.id.btnSave); //кнопка сохраненияя
    btnSave.setOnClickListener(this);
    btnLoad = (Button)findViewById(R.id.btnLoad); //кнопка загрузки
    btnLoad.setOnClickListener(this);

Farther
public void onClick(View v){
   switch (v.getId()){
       case R.id.btnSave:
           saveText();
           break;
       case R.id.btnLoad:
           loadText();
           break;
       default:
           break;
   }
}

private void saveText() {
    sPref = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor ed = sPref.edit();
    ed.putString(SAVED_TEXT, etText.getText().toString());
    ed.commit();
    Toast.makeText(MainActivity.this, "Text saved", Toast.LENGTH_SHORT).show();
}

private void loadText() {
    sPref = getPreferences(MODE_PRIVATE);
    String savedText = sPref.getString(SAVED_TEXT,"");
    etText.setText(savedText);
    Toast.makeText(MainActivity.this, "Text loaded", Toast.LENGTH_SHORT).show();
}
As a result, the application crashes with the error Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at <package name>. MainActivity.onCreate(MainActivity.java:104)
Line 104: btnSave.setOnClickListener(this);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question