TsyQi TsyQi - 6 months ago 15
Java Question

NullPointException when I use try-catch statement

Now I have an activity by which I want to call a Service named MyService.
I wrote

Intent i =new Intent(this,MyService.class);
i.putExtra("s", s);
startService(i);


in the activity,while my MyService.java typed

@Override

public void onStart(Intent intent, int startId)
{
// TODO: Implement this method
super.onStart(intent, startId);
connect(intent);
try{
connect(intent);
Intent i=new Intent();
s=i.getStringExtra("s").toString();
sendData(s);
} catch(IOError e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}


But when I run the code, I get a NullPointException on the line

s=i.getStringExtra("s").toString();


Please who can tell me where I have gone wrong,and what should I do,thanks.

Then, I got the log of my app whose package name is "com.TsyQi.Sensor"




java.lang.RuntimeException: Unable to start service com.TsyQi.Sensor.MyService@26abf3ed with Intent { cmp=com.TsyQi.Sensor/.MyService }:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference

at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2882)
at android.app.ActivityThread.access$2100(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5233)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)


Caused by:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference

at com.TsyQi.Sensor.MyService.onStart(MyService.java:227)
at android.app.IntentService.onStartCommand(IntentService.java:130)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2865)
... 9 more




Answer
 Intent i=new Intent();
 s=i.getStringExtra("s").toString();

you just create the Intent i, so it does not contain any string for the key s, making getStringExtra return null, calling toString to the null object, will make your app crash for NPE. You probably want to use the intent you get as parameter in onStart, instead of creating a new one

Comments