This is impossible. If you think about it for a while, you'll realize that that is also a nonsense. Take this code for example:
String s = getSomeString(); // assigns null
int length = s.length; // throws NPE
if (length > 10) { // what would you do here?? length is un-initialized
domeSomething();
}
Edit
Now that you've updated you question with a code snippet, there are two general approaches to deal with null
s:
1. Disallow them where they aren't supposed to be
In your code snippet, you've provided a list of EditText
s, where any o them might be null. Well, in my opinion if you have an Activity
in Android which should have some Views, then it is a programming error if any of them is null
for whatever reason. An activity without some of its views can't work properly, so throwing a NPE and exiting the application is a perfectly sensible thing to do.
The NPE tells you "hey, you've made a mistake and you have to fix it". Until then, it is not safe for the app in an unpredicted state to continue execution, because no one knows what can happen, what data can become corrupted.
2. Allow them where they make sense, and provide null-checks
There are some places where you can have variables whose value can be empty. There are several approaches how to express an empty value and null
is the most obvious one.
In that case, you can't just ignore the possibilty of a NPE and you have to do some null-checks. But again, a NPE is not your enemy. It will tell you that you've forgotten to account for all the possible situations that you should have.
Of course, repeated null checks make the code cluttered and noisy, so you can create some methods that generalize the null checks for you. I could not come up with a sensible example, so take this method only for illustration:
public void clearEditTexts(EditText... editTexts) {
for (EditText e : editTexts) {
if (e != null) {
e.setText("");
}
}
}
This method clears the contents of all the passed EditTexts. Any of them can be null, but this method does these null-checks internally, so you don't have to do it manually for each of them.
This question is also a very good reading about handling nulls:
Avoiding != null statements