1

there is this code I'm working with, and the log shows that there is an error that terminates the app like

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                  at com.example.amuna.project1.addWord.confirmBtnClicked(addWord.java:25)

and the code is

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class addWord extends AppCompatActivity {
EditText wordEdit, defEdit;
Button confirmButton;
@Override
public void onCreate(Bundle savedInstanceState) {
    wordEdit=(EditText)findViewById(R.id.wordAdd);
    defEdit=(EditText)findViewById(R.id.defAdd);
    confirmButton=findViewById(R.id.confirmBtn);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_word);
}
public void confirmBtnClicked(View v){
    SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    String newWord = wordEdit.getText().toString();
    String newDef = defEdit.getText().toString();
    editor.putString("word", newWord);
    editor.putString("def", newDef);
    editor.commit();

}
}

please help! It's String newWord = wordEdit.getText().toString(); that has an error, and please notice me if I have anything more wrong. Thanks!

이정민
  • 31
  • 5

1 Answers1

5

You should set the content view, by calling setContentView(R.layout.activity_add_word);, before wordEdit=(EditText)findViewById(R.id.wordAdd);. Change the code as follows:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_word);
    wordEdit=(EditText)findViewById(R.id.wordAdd);
    defEdit=(EditText)findViewById(R.id.defAdd);
    confirmButton=findViewById(R.id.confirmBtn);

}
Sagar
  • 23,903
  • 4
  • 62
  • 62