I'm working through an Android app I'm writing and attempting to bring my code fully in line with Android Studio's lint recommendations.
I have the following code that is issuing a warning (some code is omitted):
final EditText input = (EditText)view.findViewById(R.id.edit_text);
Button button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = input.getText().toString();
if (value == null || value.length() == 0) {
Android Studio is giving me a warning that:
Condition 'value == null' is always false.
When I allow Android Studio to "fix" the problem for me, it recommends:
Simplify 'value == null' to false
The code then becomes:
if (value.length() == 0) {
I've looked through the Android source code (http://www.grepcode.com) and I'm confused. The documentation for EditText
says "EditText is a thin veneer over TextView that configures itself to be editable." Then, the getText()
method is defined as follows:
@Override
public Editable getText() {
return (Editable) super.getText();
}
When I go to getText()
for a TextView
(the "super"), I see this:
public CharSequence getText() {
return mText;
}
The setText()
method for a TextView
appears to disallow a null
value, because this is the start of that method:
private void setText(CharSequence text, BufferType type, boolean notifyBefore, int oldlen) {
if (text == null) {
text = "";
}
The default constructor starts this way, too:
public TextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mText = "";
So, it would appear that there is no way for getText()
to return a null
value, but the comments on this answer indicate that it is. The answers to this question also seem to indicate that it is possible.
I'd like to practice defensive coding, which is why I structured my code the way I did from the beginning, but I don't want to be doing a null
check for something that cannot possibly be null
. So, what's the best practice in this case?