I have developed one application which has 15 screens. Now I want to display custom toast message in all those 15 screens. To do so, I have inflated one layout. But it's working only on one screen. So, I wrote a single method to display custom Toast
on all screens. Whenever I want to display toast message, I would just call that method. But i got java.lang.NullPointerException
. How to resolve this? The following is my code,
public static void showToastMessage(String message){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) ((Activity) context).findViewById(R.id.customToast));
// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(message);
// Toast...
Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
Log is
java.lang.NullPointerException
at com.guayama.utilities.CommonMethods.showToastMessage(CommonMethods.java:474)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
change your method
from
to
it seems context problem to me
your function will look like this
A custom class implementation of Toast that can be used in any project.
I have worked on custom toast so please follow the below process and you will use the common method for multiple time.
My custom_toast.xml is:
Second thing create one java class: like CustomToast.java
}
Third step create the object of CustomToast.java class in your activity and call the method by passing context and message.
pass
Context
in and use it asshowToastMessage(String message,Context context)
thus:
I think this is the problem,
You have not passed the context object to this method and you are trying to refer some Context Object which you could have declared globally.
So at this point if your Context Object is null you will get NullPointer. Try to pass the conetxt of your Current Activity in the parameter of your showToastMessage()