Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android toast.makeText context error

I am having trouble calling toast.Maketext inside of a location listener. The context is not available, what am I doing wrong?

private LocationListener ll = new LocationListener() {

    public void onLocationChanged(Location l) {
        // SMSReceiver.l = l;
        String s = "";
        s += "\tTime: " + l.getTime() + "\n";
        s += "\tLatitude:  " + l.getLatitude() + "°\n";
        s += "\tLongitude: " + l.getLongitude() + "°\n";
        s += "\tAccuracy:  " + l.getAccuracy() + " metres\n";
        s += "\tAltitude:  " + l.getAltitude() + " metres\n";
        s += "\tSpeed:  " + l.getSpeed() + " metres\n";

        // TODO Auto-generated method stub
        if (l.hasSpeed()) {
            mySpeed = l.getSpeed();
        }

        Log.i(DEBUG_TAG, "On Location Changed: (" + s + ")");
ERROR HERE-->       Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
    }

    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

};
like image 546
ProNeticas Avatar asked Dec 13 '22 13:12

ProNeticas


2 Answers

If this LocationListener declaration is inside an activity class (say: MyActivity), you should create the Toast as:

Toast.makeText(MyActivity.this, s, Toast.LENGTH_SHORT).show();

In case the LocationListener is declared in a contextless class, like in your case a BroadcastReceiver, you can pass the context to its constructor:

private final class MyReceiver extends BroadcastReceiver
{
    private MyLocationListener listener; 
    public MyReceiver(final Context context)
    {
        this.listener = new MyLocationListener(context);
    }

    private final class MyLocationListener implements LocationListener
    {
        private Context context;
        public MyLocationListener(final Context context)
        {
            this.context = context; 
        }

        @Override
        public void onLocationChanged(Location location)
        {
            // ...
            Toast.makeText(context, "Toast message here", Toast.LENGTH_SHORT).show();
        }

        // implement the rest of the methods
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        // Note that you have a context here, which you can use when receiving an broadcast message
    }
}
like image 138
rekaszeru Avatar answered Dec 28 '22 08:12

rekaszeru


Make sure that you use the context of the Activity class.If you are using this toast in an Activity, write, Classname.this in place of context

like image 28
Jaydeep Khamar Avatar answered Dec 28 '22 08:12

Jaydeep Khamar