Those who invented Android and Java didn't invented for themselves. Since I started developing application with Java in Android I get the most ridiculous errors and I am really going crazy (and if I do, Google and Sun Microsystems will make "booooom")
I have this simple code that is supposed to get the length of a string passed as an argument. The application just crashes, making me spend some minutes swearing and torturing the keyboard.
My code:
@Override
protected void onPostExecute(String result) {
if (result.length() == 0) {
txtStatus.setText("Ready");
}
}
If I remove the condition it works (the text "Ready" is shown on my TextView). This is something weird and I know that I might be missing some little something.
Give me some clues and thanks for everything!
P.S. If you hear a gun shoot coming from your neighbor it might be me.
Its because your string is perhaps null. Do it like this:
@Override
protected void onPostExecute(String result) {
if (!TextUtils.isEmpty(result)) {
txtStatus.setText("Ready");
}
}
Try this:
@Override
protected void onPostExecute(String result) {
if (result != null && result.length() == 0) {
txtStatus.setText("Ready");
}
}
Check if result is null first, Handle it appropriately, then check it's length. My best guess is you have an unhandled NullPointerException.
@Override
protected void onPostExecute(String result) {
if (result == null) {
result = ""; // change this line if null is an error.
}
if (result.length() == 0) {
txtStatus.setText("Ready");
}
}
A debugging technique to figure out what is wrong and making your program crash would be to wrap the condition in a try/catch block.
@Override
protected void onPostExecute(String result) {
try {
if (result.length() == 0) {
txtStatus.setText("Ready");
}
catch (Throwable t) { // both error and exception inherit from Throwable.
// print or inspect 't' here to determine the reason for the crash.
}
}
As said by Waqas the problem is because your string maybe null. If the string is null the method length is not defined.So add an additional condition checking for null i.e
if(result ==NULL)
// do something else
else
//your code here