I’m currently working on my project, and I’ve got a problem.
My app crashes when it comes to SearchDic().
Here’s my code:
public int SearchDic(final CharSequence received) {
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run(){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.endic.naver.com/search.nhn?query=" + received + "&searchOption=entryIdiom&preQuery=&forceRedirect="));
startActivity(browserIntent);
}}, 10);
return 0;
}
The service in my app calls this SearchDic(), so I used non-static way… such as
// Local Variable Received
MainActivity a = new MainActivity();
a.SearchDic(Received);
I’ve tried Logcat, but it keeps crashing on the startActivity() part, and I could see the error message, java.lang.NullPointerException.
Here’s my Logcat Errors:
08-17 16:16:10.364: D/AndroidRuntime(19322): Shutting down VM
08-17 16:16:10.364: W/dalvikvm(19322): threadid=1: thread exiting with uncaught exception (group=0x40c7c1f8)
08-17 16:16:10.369: E/AndroidRuntime(19322): FATAL EXCEPTION: main
08-17 16:16:10.369: E/AndroidRuntime(19322): java.lang.NullPointerException
08-17 16:16:10.369: E/AndroidRuntime(19322): at android.app.Activity.startActivityForResult(Activity.java:3252)
08-17 16:16:10.369: E/AndroidRuntime(19322): at android.app.Activity.startActivity(Activity.java:3359)
08-17 16:16:10.369: E/AndroidRuntime(19322): at com.wjuni.easydic.MainActivity$1.run(MainActivity.java:80)
08-17 16:16:10.369: E/AndroidRuntime(19322): at android.os.Handler.handleCallback(Handler.java:605)
08-17 16:16:10.369: E/AndroidRuntime(19322): at android.os.Handler.dispatchMessage(Handler.java:92)
08-17 16:16:10.369: E/AndroidRuntime(19322): at android.os.Looper.loop(Looper.java:137)
08-17 16:16:10.369: E/AndroidRuntime(19322): at android.app.ActivityThread.main(ActivityThread.java:4514)
08-17 16:16:10.369: E/AndroidRuntime(19322): at java.lang.reflect.Method.invokeNative(Native Method)
08-17 16:16:10.369: E/AndroidRuntime(19322): at java.lang.reflect.Method.invoke(Method.java:511)
08-17 16:16:10.369: E/AndroidRuntime(19322): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
08-17 16:16:10.369: E/AndroidRuntime(19322): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
08-17 16:16:10.369: E/AndroidRuntime(19322): at dalvik.system.NativeStart.main(Native Method)
What’s problem in my application, and how should I call this function? Please help me.
Thanks.
As @jens pointed out you should not initialize MainActivity by yourself.
StartActivity is failing becasue the context of the Activity is not initialized. You need to use your Service’s Context. Use below function . Copy this function to your own service.