public void addEventTime(String eTimesIn)
{
if (numETimes == eTimes.length) {
increaseEventTimesCapacity();
}
eTimes[eTimes.length - 1] = eTimesIn;
}
Straight from the Docs:
Thrown when an application attempts to use null in a case where an
object is required. These include:
Calling the instance method of a
null object.
Accessing or modifying the field of a null object.
Taking
the length of null as if it were an array.
Accessing or modifying the
slots of null as if it were an array.
Throwing null as if it were a
Throwable value.
I would guess your eTimes[eTimes.length - 1] = eTimesIn; is trying to access a null.
Related
I'm new to Android Studio.
I'm getting
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String
com.alpha1.appname.rider.model.firebase.User.getName()' on a null
object reference.
Can anyone point me in the right direction. I can't seem to fix with the answers on the other similar questions.
\Here is the line that is producing the null pointer exception\
private void setDriverData() {
View navigationHeaderView = navigationView.getHeaderView(0);
TextView tvName = navigationHeaderView.findViewById(R.id.tvDriverName);
TextView tvStars = navigationHeaderView.findViewById(R.id.tvStars);
CircleImageView imageAvatar= navigationHeaderView.findViewById(R.id.imageAvatar);
tvName.setText(Common.currentUser.getName());
if(Common.currentUser.getRates() != null &&
!TextUtils.isEmpty(Common.currentUser.getRates()))
tvStars.setText(Common.currentUser.getRates());
if(Common.currentUser.getAvatarUrl()!=null &&
!TextUtils.isEmpty(Common.currentUser.getAvatarUrl()))
Picasso.get().load(Common.currentUser.getAvatarUrl()).into(imageAvatar);
This is the problematic line:
tvName.setText(Common.currentUser.getName());
The error message tells you that you cannot call getName of null. This means that Common.currentUser is null. Something being null means that it is not defined. Referring data members or calling methods of something that does not exist will yield this error. You can fix this issue by properly initializing Common.currentUser before that line executes, or defaulting it if it was not defined, like:
tvName.setText((Common.currentUser == null) ? "" : Common.currentUser.getName());
bitmap1 = Bitmap.createScaledBitmap(
bitmap1, // <---- error is here
(width.toInt()),
(height.toInt()),
false)
numberOfInvaders ++
I also used bitmap2 and bitmap 1 in another class :
if (uhOrOh) {
canvas.drawBitmap(Invader.bitmap1, // <--- error is here
invader.position.left,
invader.position.top,
paint)
} else {
canvas.drawBitmap(Invader.bitmap2, // <---- and here
invader.position.left,
invader.position.top,
paint)
}
here its says : Type mismatch,
Required:Bitmap Found: Bitmap?
Yup, that's true :) You cannot use value like this, because it can be null at some point.
createScaledBitmap requires nonnullable Bitmap, but there is no guarantee that bitmap you use won't be null at the moment of calling given function.
So, what you can do?
Before the call check if bitmap is not null:
if (bitmap != null) { /* code here, still requires !! operator */ }
In multithreaded environment there is a risk that during execution of code block a value will change anyway, so you can use let function with ?. operator (basically the same operator like ., but executes only if value is not null). The block code will be invoked with an effectively final argument which is an instance you use to call this method, in this case "bitmap", called "context object", accessible via it keyword:
bitmap?.let { /* code here, bitmap is passed as effectively final, so for sure it's not null */ }
There other way would be !! operator (but it can finish with NPE exception, if value is null). Use only if you are sure that this value at that moment won't be null, otherwise you can crash your application.
Also, you can use ?: operator - this will take first value if not null, otherwise the second. It's quite nice, because you can use for example default value. Also, you can throw exception there ;)
bitmap ?: throw IllegalStateException("bitmap is null") // exception
bitmap ?: DEFAULT_BITMAP // default bitmap, if any
In this case you will get exception but with very communicative message (instead of just NPE).
bitmap1 = Bitmap.createScaledBitmap(
bitmap1!!, // !! <--- helps
(width.toInt()),
(height.toInt()),
false)
numberOfInvaders ++
if (uhOrOh) {
canvas.drawBitmap(Invader.bitmap1!!, // here
invader.position.left,
invader.position.top,
paint)
} else {
canvas.drawBitmap(Invader.bitmap2!!, // and here too
invader.position.left,
invader.position.top,
paint)
}
In my code, I have a reference variable LogValidacionPagosDTO
public void InsertarArchivoXmlOk(ArchivoXmlDRO archivo, ref LogValidacionPagosDTO archivoRespuesta)
{
//Some code
}
When executing "code analysis" generates this warning
Warning CA1062
In externally visible method 'ArchivoXMLOperacion.ValidacionDuplicadosArchivoXmlFosyga(List<RegistroXmlFosygaDRO>, ref LogValidacionPagosDTO)',
validate local variable ''(*archivoRespuesta)'', which was reassigned from parameter 'archivoRespuesta', before using it.
Then try to validate the object as null
public void InsertarArchivoXmlOk(ArchivoXmlDRO archivo, ref LogValidacionPagosDTO archivoRespuesta)
{
if (archivoRespuesta == null || archivoRespuesta.DetalleRegistros == null)
throw new ExcepcionOperacion(HelperMensaje.Obtener(HelperCodigoMensaje.GEN_0003),
(int)CodigosHTTP.Error, archivoRespuesta, null);
//Some code
}
But this didn't solve the warning. I found this possible solution in Microsoft forum https://social.msdn.microsoft.com/Forums/en-US/fdb00899-c7ea-4e8e-b5f6-9768c2ac0001/ca1062-false-positive-in-externally-visible-method-xxx-validate-local-variable-x-which-was?forum=vstscode
But, I really need to know if this is a false positive, thks!
public void onSearch(View view)
{
EditText location_tf = (EditText)findViewById(R.id.TFaddress);
String location = location_tf.getText().toString();
List<Address> addressList = null;
if(location != null || location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try {
geocoder.getFromLocationName(location,1);
}
catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0); //error line
LatLng latLng = new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(" Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
Since addressList is being set to null in the beginning and not being modified until you call get(0), it will cause an error.
List<Address> addressList = null;
...
addressList.get(0); // you cannot call a method of a null object
In order to fix this, you have to fetch the addresses from somewhere - i.e. via another method call.
As others have pointed out, the variable addressList is guaranteed to be null at that point, so a NullPointerException is guaranteed on that line.
And as others have mentioned, to circumvent the error, you need to assign the variable to something other than null or omit the line entirely.
Something that others haven't pointed out yet is that--if you do assign the variable to a non-null reference--you should also check that the list is not empty. Otherwise, you will get a different kind of error when you try to get an element by its index. This is the general contract of the List interface's get method.
In below code I want to neutralize the throw and continue the method - Can it be done ?
public class TestChild extends TestParent{
private String s;
public void doit(String arg) throws Exception {
if(arg == null) {
Exception e = new Exception("exception");
throw e;
}
s=arg;
}
}
The net result should be that, in case of the exception triggered (arg == null)
throw e is replaced by Log(e)
s=arg is executed
Thanks
PS : I can 'swallow' the exception or replace it with another exception but in all cases the method does not continue, all my interventions take place when the harm is done (ie the exception has been thrown)
I strongly doubt that general solution exists. But for your particular code and requirements 1 and 2:
privileged public aspect SkipNullBlockAspect {
public pointcut needSkip(TestChild t1, String a1): execution(void TestChild.doit(String))
&& this(t1) && args(a1) ;
void around(TestChild t1, String a1): needSkip(t1, a1){
if(a1==null) //if argument is null - doing hack.
{
a1=""; //alter argument to skip if block.
proceed(t1, a1);
t1.s=null;
a1=null; //restore argument
System.out.println("Little hack.");
}
else
proceed(t1, a1);
}
}
I think that generally what you want makes no sense most cases because if an application throws an exception it has a reason to do so, and that reason almost always includes the intention not to continue with the normal control flow of the method where the exception was thrown due to possible subsequent errors caused by bogus data. For example, what if you could neutralise the throw in your code and the next lines of code would do something like this:
if(arg == null)
throw new Exception("exception");
// We magically neutralise the exception and are here with arg == null
arg.someMethod(); // NullPointerException
double x = 11.0 / Integer.parseInt(arg); // NumberFormatException
anotherMethod(arg); // might throw exception if arg == null
Do you get my point? You take incalculable risks by continuing control flow here, assuming you can at all. Now what are the alternatives?
Let us assume you know exactly that a value of null does not do any harm here. Then why not just catch the exception with an after() throwing advice?
Or if null is harmful and you know about it, why not intercept method execution and overwrite the parameter so as to avoid the exception to begin with?
Speculatively assuming that the method content is a black box to you and you are trying to do some hacky things here, you can use an around() advice and from there call proceed() multiple times with different argument values (e.g. some authentication token or password) until the called method does not throw an exception anymore.
As you see, there are many ways to solve your practical problem depending on what exactly the problem is and what you want to achieve.
Having said all this, now let us return to your initial technical question of not catching, but actually neutralising an exception, i.e. somehow avoiding its being thrown at all. Because the AspectJ language does not contain technical means to do what you want (thank God!), you can look at other tools which can manipulate Java class files in a more low-level fashion. I have never used them productively, but I am pretty sure that you can do what you want using BCEL or Javassist.