问题
My code is
Context c = getApplicationContext();
CharSequence c1 = "Invalid Data Entered";
Toast t= Toast.makeText(c, c1, Toast.LENGTH_SHORT);
t.show();
it showing NULL POINTER EXCEPTION AT Toast.makeText() line
Any help..? thanks..
回答1:
It was actually because i was calling it from a different class and not an activity.. that was the reason.. IV can't create Toast in an Activity which is not running..
回答2:
you just have to use your view instead of getApplicationContext() for example if it is rowView just call :
Toast.makeText(rowView.getContext, " " ,Toast.LENGTH_SHORT).show();
回答3:
Maybe I am being blind, but the only thing I can see that could be null is your
getApplicationContext();
Check if that's null, and have it log it if it is, so you know the cause.
Can you show the code surrounding it please?
回答4:
try this and check.
Context c = getBaseContext();
CharSequence c1 = "Invalid Data Entered";
Toast t= Toast.makeText(c, c1, Toast.LENGTH_SHORT);
t.show();
or Toast t= Toast.makeText(activity, c1, Toast.LENGTH_SHORT);
you can also use activity instead of context..
回答5:
Try to use this:
Toast t= Toast.makeText(YourActivity.this, c1, Toast.LENGTH_SHORT);// YourActivity is the class name
for showing toast.
回答6:
The issue may be in line Context c = getApplicationContext();
if context is null then you will get NULLPOINTER EXCEPTION in Toast t= Toast.makeText(c, c1, Toast.LENGTH_SHORT);
You can use the following if your class extends Activity
Toast t= Toast.makeText(Classname.class, c1, Toast.LENGTH_SHORT);
or
Toast t= Toast.makeText(this, c1, Toast.LENGTH_SHORT);
If your class doesnot extend Activity better pass the context value to this class from the calling environment. after that use that context to create Toast
Thanks Deepak
回答7:
Context c=getApplicationContext();
Toast t=Toast.makeText(c, "invalid data enterd", Toast.LENGTH_SHORT);
t.show();
I tried this and it is working...
回答8:
Write this..
Toast t = Toast.makeText(this, "Invalid Data Entered", Toast.LENGTH_SHORT);
t.show();
回答9:
First of all check if you are calling toast.show() method inside an activity . Because toast is meant to show on user screen and you can not show it outside like service or non activity class . If you are trying to show toast some where in activity your code should work.
来源:https://stackoverflow.com/questions/6196960/error-when-creating-toast