Search code examples
android-fragmentshandlerandroid-contextandroid-toast

Passing Activity Context to Handler(fragment) for Toast


I'm trying to use a Toast message in a handler fragment class but I can't access the main class' context. The handler is in the same class as the main activity, PlayFrets(which is also the UI thread).I've read through the plethora of questions on this topic on stackoverflow, but almost every solution involves passing getActivity() or getActivity().getApplicationContext() into the context field of Toast. When I try this I get errors

Here is the relevant code:

public class PlayFrets extends Activity {
. 
.
.
    static Handler mHandler = new Handler(Looper.getMainLooper()){  
        public void handleMessage(final Message msg){ 
            if(msg.obj != null){                
                runOnUiThread(new Runnable() {
                   public void run() {
                   //error happens here on Toast message
                       Toast.makeText(getActivity(), "Background Thread sent "+  msg.what + " bytes: " + msg.obj,Toast.LENGTH_SHORT).show();
                    }
                });
            }
            else{
            }
        }
    };
}

These are my attempts at passing the context and the errors each variation generates.

Toast.makeText(PlayFrets.this.getActivity()...)

^^^The method getActivity() is undefined for the type PlayFrets

Toast.makeText(PlayFrets.this...) 

^^^No enclosing instance of the type PlayFrets is accessible in scope

 Toast.makeText(getActivity().getApplicationContext()...)

^^^The method getActivity() is undefined for the type new Runnable(){}

What is the proper way to pass the main activity's context into the handler fragement for use in a Toast message?


Solution

  • Activity is a context itself. Instead of all things you try you should

    • not create static handler - that's why your attempt to pass PlayFrets.this fails
    • pass PlayFrets.this as context
    • no need to call runOnUiThread() because handler handles messages on UI thread in presented case

    Your handler code should look like this:

    Handler mHandler = new Handler() {  
        public void handleMessage(final Message msg){ 
            if(msg.obj != null){
                       Toast.makeText(PlayFrets.this, "Background Thread sent "+  msg.what + " bytes: " + msg.obj,Toast.LENGTH_SHORT).show();
            }
            else{
            }
        }
    };