Search code examples
androidandroid-activitytoast

Cannot show toast from a non-activity class (Android)


I wrote a messaging application and I want to notify users when some other user message them. But I cannot keep track of it in my ContactListActivity so I try to show it in my connection.java class.(Simply, pop-up a text when viewing contactList if a new message arrives). Here is what I tried to do

private  final Context mApplicationContext;
public Connection(context c){
 mApplicationContext = c.getApplicationContext();
/....
}
  System.out.println("Print something");
  Toast.makeText(mApplicationContext, " You received a  message from "+contactJid, Toast.LENGTH_LONG).show(); //Is called everytime when I receive a message.
  System.out.printnl("Print something");  // I can print both, I receive the message but toast does not appear

Dont worry about the variable names. How can I accomplish my goal? I use mApplicationContext in other places and it does what I want it to do.

I also tried with creating a new ContactListActivity object in this class and get its application context it also failed Constructive feedback is appreciated so I can make the question clearer.


Solution

  • If you are getting response in Logs then it might be an issue of non UI thread. Nothing will update or show on UI from worker thread so update your UI from main thread only.

    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
        //Here you can update your UI
        }
    });