EditText.getText()。toString()错误

时间:2018-08-06 02:06:22

标签: android android-edittext

有我正在使用的这段代码,并且日志显示有一个错误会终止应用程序,如

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)

代码是

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

}
}

请帮助!它是字符串newWord = wordEdit.getText()。toString();出现错误,如果还有其他错误,请注意。谢谢!

1 个答案:

答案 0 :(得分:5)

您应该通过在setContentView(R.layout.activity_add_word);之前调用wordEdit=(EditText)findViewById(R.id.wordAdd);来设置内容视图。更改代码,如下所示:

@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);

}