Android toast.makeText 上下文错误
我在位置侦听器内调用 toast.Maketext 时遇到问题。上下文不可用,我做错了什么?
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
}
};
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
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
声明位于活动类内部(例如:
MyActivity
),则应将Toast
创建为:如果此
LocationListener
在无上下文类中声明,就像您的例子中的BroadcastReceiver
一样,您可以将上下文传递给其构造函数:If this
LocationListener
declaration is inside an activity class (say:MyActivity
), you should create theToast
as:In case the
LocationListener
is declared in a contextless class, like in your case aBroadcastReceiver
, you can pass the context to its constructor:确保使用 Activity 类的上下文。如果您在 Activity 中使用此 toast,请编写 Classname.this 代替 context
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
由于上下文不可用,您可以将其传递到构造函数中
Since context is not available,you can pass it in constructor