I try to pass a type variable long
to a service which is the time in which it will be executed but I get the following error
9-27 00:33:16.364 14153-15553/com.android.controlmovil E/AndroidRuntime: FATAL EXCEPTION: IntentService[enviar_coord_background]
Process: com.android.controlmovil, PID: 14153
java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:124)
at java.lang.Long.parseLong(Long.java:345)
at java.lang.Long.parseLong(Long.java:321)
at com.android.controlmovil.enviar_coord_background.onHandleIntent(enviar_coord_background.java:70)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.os.HandlerThread.run(HandlerThread.java:61)
My code is
Intent intent1 = new Intent(enrolar_ws.this, enviar_coord_background.class);
intent1.putExtra("rango",rango_spinner);
startService(intent1);
And in my service it is
@Override
protected void onHandleIntent(Intent intent) {
boolean band=false;
long rango;
try {
rango = Long.parseLong(intent.getStringExtra("rango"));
while(band==true){
try {
Thread.sleep(rango);
comenzarLocalizacion(enviar_coord_background.this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}catch (NullPointerException e){
Toast.makeText(getApplicationContext(),"Error"+e,Toast.LENGTH_LONG).show();
}
//}
}
The problem specified in your LogCat is :
Since inside your method it
onHandleIntent()
tries to perform a parse to convert a value to long, but this value is null.You could quickly perform a validation to avoid this problem:
But it is important to check because the value you send is null from the intent, you could perform a validation through a ternary operation:
The problem is that when you put the
long
extrarango_spinner
, its value isnull
.You should do a check, check if the value is
null
to not start the service and show a message to the user.For example:
So far the first problem, but...
null
there is oneNumberFormatException
instead of oneNullPointerException
?What happens next is that you get the extra back as a
String
, since you useintent.getStringExtra("rango")
, so you don't get backnull
aslong
, but asString
, so you try to parse the string"null"
which causes the:To avoid this, insert like this:
I have done a simple casting, but maybe you should convert it with
Long.valueOf
or similar .And recover the extra with
Intent::getLongExtra(java.lang.String, long
) , with which you will also have a default value in case you do not want to perform the first proposed check and you may receive erroneous data.EXTRA : in case you want to know what is happening, here is the implementation of
getLongExtra
: