Wednesday, July 27, 2011

[android-developers] Calling addTextChangedListener BEFORE setInputType crashes, but AFTER is fine

Hello all, this may be a problem in my code, but it could also be a
potential problem in the API, and I'd like to point it out to the
community with hopes that the platform's official developers at Google
see this (and chances are they probably know, but I thought I'd point
it out anyway).

I'm dynamically creating an EditText view in Java, a password field
(which I define as such with setInputType). I have a very simple
TextWatcher that I'm adding as a textChangedListener to this
EditText. Here's my code:

TextWatcher textWatcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence paramCharSequence,
int paramInt1, int paramInt2, int paramInt3)
{
}

public void onTextChanged(CharSequence paramCharSequence, int
paramInt1, int paramInt2, int paramInt3)
{
updateUI();
}

public void afterTextChanged(Editable paramEditable)
{
}
};

passwordET = new EditText(activity);
passwordET.setHint("Password");
passwordET.addTextChangedListener(textWatcher);
passwordET.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);

When it calls setInputType, a NullPointerException is thrown.
HOWEVER, if I swap that call with the call to addTextChangedListener,
like so:

passwordET = new EditText(activity);
passwordET.setHint("Password");
passwordET.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
passwordET.addTextChangedListener(textWatcher);

Then no exception is thrown - everything's fine.

I tested this on android OS's 1.6 and 3.1, results on both OS versions
were the same. Was wondering if anyone could shed some light on this
issue, or if this is a potential problem in the API. Thanks for your
insight!

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment