EditText.getText().toString() error [duplicate]
Clash Royale CLAN TAG#URR8PPP
EditText.getText().toString() error [duplicate]
This question already has an answer here:
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!
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
wordEdit
you need to bind your views after setContentView(..)
– MRah
Aug 6 at 2:09
1 Answer
1
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:
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);
Okay, I'll try that!
– 이정민
Aug 6 at 2:15
Thanks! I think it worked! The app doesn't quit any more!
– 이정민
Aug 6 at 2:17
@이정민 great! Remember to mark answer as accepted so that others can benefit too
– Sagar
Aug 6 at 2:42
And one more thing, remember to call
super
just after the method name.– meditat
Aug 6 at 2:45
super
Ok, I just marked your answer and Thank you again! It works very well!
– 이정민
Aug 6 at 3:25
Did you debug and verify that
wordEdit
in fact is being initialized to a non null reference?– Tim Biegeleisen
Aug 6 at 2:08