0

I have a strange error, I get NullPointerException error when I set text to EditText. Code is something like below:

EditText editTxt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    editTxt = (EditText) findViewById(R.id.edtTxt);
    if(someCondition) {
        if (editTxt!=null)
            editTxt.setText("HelloWorld");
        }
    }
}
3
  • 2
    Post your logcat please. Commented Feb 7, 2012 at 10:59
  • Post your layout and Exception log please. Commented Feb 7, 2012 at 10:59
  • 1
    Please post the original code. Commented Feb 7, 2012 at 11:01

4 Answers 4

1

in this small code,There should be one Error only

    editTxt = (EditText)findViewById(R.id.edtTxt);

that your id in xml doesnot match with edtTxt.If yes then try to clean it once then run

Sign up to request clarification or add additional context in comments.

4 Comments

there is a check for if(editTxt!=null), so it should not cause the exception.
when you will setValue then it gave exception.If you check it it did not satisfy null condition if(editTxt!=null)
//Got it working like this, String hello = "HelloWorld!"; EditText editTxt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editTxt = (EditText)findViewById(R.id.edtTxt); if(someCondition) {if(editTxt!=null) editTxt.setText(hello); } }
so that means there was not error.Will you consider to accept this answer?
0

The object that's cited in the stack trace wasn't initialized. You never asked it to point to a new object on the heap.

I'm putting my money on that reference R. I don't see where that's initialized.

Comments

0

Please try this code:

EditText editTxt = (EditText) findViewById(R.id.text);

if (editTxt!=null) {
    editTxt.setText("HelloWorld");
}

Comments

0
//Got it working like this, 
String hello = "HelloWorld!"; 
EditText editTxt; 
@Override public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    editTxt = (EditText)findViewById(R.id.edtTxt); 
    if(someCondition) {
        if(editTxt!=null) editTxt.setText(hello); 
    } 
} 

1 Comment

No clue why string constant entered directly was not working thou !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.