InvocationTargetException and a coding discussion - android

This code is throwing a invocationTargetException.
There are a few problems with this code:
It is still entering the if statement even though I specifically told it not too when nothing is input into the EditText.
I am guessing the exception could have occurred because of the parseInt not having anything to parse (Although that shouldn't be a problem).
A cause of this type exception should be not initiating something at the right time, should it not?
if(ageText.getText().toString() != "" || ageText.getText().toString() != null)
{
newCharacterController.characterAge = Integer.parseInt(ageText.getText().toString());
}
A little off topic too, I cant seem to find the tag of any of the containers like a Spinner or EditText, when I look into the mTag value of it when the program is running, will this affect my if(parent.getTag() == "OBJECTIDGIVENBYMYSELF") and stop if from working? Also is there a better way to gain the tag value (.getType() in C#).
An example of the above OBJECTNAMEGIVENBYMYSELF is EditText ***newEditText*** = new EditText(this);.

ageText.getText().toString() != ""
The above code is not a good practice to compare String content, simply because comparison operator such as "==" is used to compare by reference but not value. I think you should use the following code instead
ageText.getText().toString().equals("")
And by the way, check null before this.

Related

NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null. Receiver: null Tried calling: length) [duplicate]

I have some code and when I run it produces an error, saying:
NoSuchMethod: the method 'XYZ' was called on null
What does that mean and how do I fix it?
Why do I get this error?
Example
As a real world comparison, what just happened is this conversation:
Hey, how much gas is left in the tank of the car?
What are you talking about, we don't have a car.
That is exactly what is happening in your program. You wanted to call a function like _car.getGasLevel(); but there is no car, the variable _car is null.
Obviously, in your program it might not be a car. It could be a list or a string or anything else really.
Technical explanation
You are trying to use a variable that is null. Either you have explicitly set it to null, or you just never set it at all, the default value is null.
Like any variable, it can be passed into other functions. The place where you get the error might not be the source. You will have to follow the leads from the actual null value to where it originally came from, to find what the problem is and what the solution might be.
null can have different meanings: variables not set to another value will be null, but sometimes null values are used by programmers intentionally to signal that there is no value. Databases have nullable fields, JSON has missing values. Missing information may indeed be the information itself. The variable bool userWantsPizzaForDinner; for example might be used for true when the user said yes, false when the user declined and it might still be null when the user has not yet picked something. That's not a mistake, it's intentionally used and needs to be handled accordingly.
How do I fix it?
Find it
Use the stack trace that came with the error message to find out exactly which line the error was on. Then set a breakpoint on that line. When the program hits the breakpoint, inspect all the values of the variables. One of them is null, find out which one.
Fix it
Once you know which variable it is, find out how it ended up being null. Where did it come from? Was the value never set in the first place? Was the value another variable? How did that variable got it's value. It's like a line of breadcrumbs you can follow until you arrive at a point where you find that some variable was never set, or maybe you arrive at a point where you find that a variable was intentionally set to null. If it was unintentional, just fix it. Set it to the value you want it to have. If it was intentional, then you need to handle it further down in the program. Maybe you need another if to do something special for this case. If in doubt, you can ask the person that intentionally set it to null what they wanted to achieve.
simply the variable/function you are trying to access from the class does not exist
someClass.xyz();
above will give the error
NoSuchMethod: the method 'xyz' was called on null
because the class someClass does not exist
The following will work fine
// SomeClass created
// SomeClass has a function xyz
class SomeClass {
SomeClass();
void xyz() {
print('xyz');
}
}
void main() {
// create an instance of the class
final someClass = SomeClass();
// access the xyz function
someClass.xyz();
}

Android Studio complains of expression being null even after check

I have the following line of code in onCreateView() method of my Fragment. It warns me that the expression to createPinPresenter.setLoginResult() can be null.
So I ask AS to generate the null check and it does this.
Even after the auto generated code, AS still complains the same expression being null. It obviously cannot be null inside the check.
Am I missing something obvious here or is this a bug?
Edit: I'm using AS version 2.2.3
This is correct, how does AS know if, for example, getParcelable() will return the same value? it is just a syntactic control, not a semantic control.
A function could return, for example, null if the number of times it has been called is odd: in that case the warning is correct.
Think this:
if (getNextValue() != null)
value = getNextValue();
If getNextValue() increments an index, at the end of an array it could return null: the error is pretty obvious, and it's actually what the control tries to prevent in your code.
The only solution is to store the result of getParcelable(KEY_LOGIN_RESULT) in a temporary variable, in that case AS will correctly manage it.
And of course... the fact that this is an autogenerated code, is actually a bug, I think, of the autogeneration, that is less smart than the control.

xBest Practice to check for NullPointerException

To get better programming skills, I read some sources from others.
I ask myself everytime, what the best way of validation is.
Here you will find some seafile code snippets for android. I'm wondering, why nobody will check in line 109, if ActionBar is null.
On other posts here on SO, I found something like this:
TextView Foo = (TextView) findViewById(R.id.FooBar)
In that post it was said, that this can result in a NullPointer or CastException. That's right. Unfortunately, even Google doesn't do this validation in its own reference.
Do you have any idea, how to deal with it? When should I check, if something is Null or not?
In my opinion
TextView Foo = (TextView) findViewById(R.id.FooBar)
is an example in which it's either always null or never null or CastException or no exception. So I'd not check it for null or check for that exception, since it never changes. If it runs once, it will always run ;)
I'd rather concentrate on checking for null whenever the result actually can be null or not null.

Try-Catch: Is it OK to leave applications with handled exceptions?

I am still fairly new to programming, so there are some things I learn from observing but do not fully understand. The Try-Catch is one of these things. From what I have researched, the try statement allows me to define a block of code to be tested for errors, and the catch statement allows me to define a block of code to be executed if an error occurs in the try block.
I get that. And I have tried to use Try-Catch in situations where I was receiving exception errors that crashed my applications. The Try-Catch seemed to prevent (stop) the crashing. But here is my question, is it OK to have an application that constantly catches an exception error?
For example, I am working with EditText widget. I want the input values for the EditText to represent currency, so I applied android:inputType="numberDecimal". The issue I learned with this is that this attribute allows any number of values after the decimal. This is when I came up with an idea of updating the EditText programmically with the proper format, using something like DecimalFormat.
I am not posting my entire code, but here is the piece that I am curious about.
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
DecimalFormat format = new DecimalFormat("0.00");
if (etBill.getText().toString() != null &&
etBill.getText().toString().length() > 0) {
try {
doubleBill = Double.parseDouble(etBill.getText().toString());
strFormatted = format.format(doubleBill);
Log.d(TAG, "unformatted(" + doubleBill + ")" +
" // formatted(" + strFormatted + ")");
//etBill.setText("$" + strFormatted, TextView.BufferType.EDITABLE);
etBill.setText("$" + strFormatted);
} catch (NumberFormatException nfe) {
Log.e(TAG, "FloatingPointParser.parseDouble error");
}
} else {
// values in editText were deleted; hardcode value
doubleBill = 0.0;
strFormatted = format.format(doubleBill);
}
}
And here is the exception error I catch every single time I input a value into my EditText widget.
So my question is, is the Try-Catch a method for me to correct my errors? Is it OK to catch exception errors, such as this NumberFormapException through the life of an application running? Am I using this right? Thanks in advance!
NumberFormatException is a runtime exception and you are catching it correctly. However, instead of just printing something to let you know you have caught it, you should either handle it by re-running through your code or pass the exception up the stack. For example, if a user inputs a number and then this exception is caught, you could prompt them to re-enter a new number. If the number that is throwing this exception is not provided by a user, but by your code, then it indicates you have a logic error somewhere and should fix that to prevent this exception from being thrown in the first place.
In general the exception mechanism should be used for exceptional circumstances - something that usually shouldn't happen. If you have an exception that's being thrown every time you enter a value, that's sort of abusing the mechanism. Usually there's a better way that doesn't involve exceptions. In some cases though, the exception mechanism is the cleanest way of dealing with the situation.
Here's a quote from Effective Java: Programming Language Guide by Josh Bloch:
"Use exceptions only for exceptional conditions. That is, do not use exceptions for control flow, such as catching NoSuchElementException when calling Iterator.next() instead of first checking Iterator.hasNext()."
Exception handling is not only an art but the subject of much discussion/debate. I will try to address the broader points without incurring anyone's wrath.
There are two kinds of exceptions--fault exceptions and contingency exceptions. Fault exceptions are unrecoverable like being unable to connect to a web service that is supposed to be there for your app to function. You log those in your catch block and rethrow to let them bubble to some fault handler. Contingency exceptions are what you described with the number format issue--stuff you can recover from. In this case, you handle things completely in the catch block. You allow the app to recover by prompting for a new input, for example.
By the way, none of that is my own. That strategy comes from Barry Ruzek.
Then there is the issue where people dislike using exceptions for flow control--for good reason. In your case, that would mean using a regular expression in an if statement, for example, to test number format rather than using a potential exception-generating operation. You generally don't want to use exceptions for normal control flow, but you also need to be careful not to let ideology trump a simple solution. There is a balance you will learn with experience.
So you should recover from the exception in your catch block. Or use a different non-exceptional mechanism entirely to manage control flow.
Hope that helps.
Using Try catch in programing is fair enough. But handling errors is different issue. Try catch is just to way catch erronious conditions which can occur in ur program but u may wish to catch it or leave its up to you. Simple example is age is not allowed as floating point number but height is allowed both floating point and decimal number.

There are 2 Log.i statements in the script. Only the 2nd one shows up

here is the code snippet
Log.i("poweruptcoach:aboutx000",MainActivity.pathtocoach);
if(MainActivity.pathtocoach != null && !MainActivity.pathtocoach.isEmpty()){
filespec = ServerFileSpec + MainActivity.pathtocoach;
}
topstuff = (RelativeLayout)findViewById(R.id.topstuff);
Button coachesBtn = (Button)findViewById(R.id.coachesBtn);
Button disclaimerBtn = (Button)findViewById(R.id.disclaimerBtn);
Log.i("poweruptcoach:aboutx00","?" +MainActivity.pathtocoach+"?");
The first log-aboutx000, does not appear in catlog, but the second one-aboutx00, does. WHY?
Well, since they're using different tags, that's the first thing I'd be checking.
It may be that you're filtering on the tagname. You can set properties to indicate at what log level each tag is allowed to log, and check this programatically with isLoggable().
It should be easy to see if this is the case by simply changing the tag on the first one to match the second one, and seeing if it appears after that.
Humorous aside: I've just noticed that the Log class contains a few wtf() methods, supposedly for "What a terrible failure". That's not a very believable acronym, it's similar to Alex's renaming of "The Daily WTF" to mean "worse than failure" - I think we all know what this really stands for :-)

Categories

Resources