Why does showing Toast outside onCreate () crash my application?

old question: "Why does creating a toast break my application?"

My application works fine if I don't use toasts, but if I want to create and show a simple toast like this:

   Toast SimpleToast = Toast.makeText(getApplicationContext(), "Just a toast.",Toast.LENGTH_LONG);
   SimpleToast.setGravity(Gravity.TOP, 0, 0);
   SimpleToast.show();

I get these lines in the log, and then the application crashes:

NotificationService   enqueueToast pkg=games.MyAppName callback=android.app.ITransientNotification$Stub$Proxy@49603368 duration=1
ResourceType          No package identifier when getting name for resource number 0x00000000
AndroidRuntime        Shutting down VM
dalvikvm              threadid=3: thread exiting with uncaught exception (group=0x4001b188)
AndroidRuntime        Uncaught handler: thread main exiting due to uncaught exception
AndroidRuntime        java.lang.NullPointerException

I checked and double checked the above code, which causes it to crash. I am running an emulator since I currently do not have an Android phone.

+3
source share
6 answers

, "", . , , URL- , , .

onCreate , , / .

+1

, , Activity. , , . getApplicationContext() ctx, .

!

+2

- getApplicationContext null. "ActivityName.this" onClick() .

+1
@Override
public boolean onTouch(View V, MotionEvent event) {
 ...
 Toast toast = Toast.makeText(V.getContext(), ...

V - , . appConntext() .

+1

, -, , . .setGravity. , Toast.makeText . , Activity Service.

0

try-catch . , Activity , .

0

Source: https://habr.com/ru/post/1750886/


All Articles