【问题标题】:the method getApplicationContext() is undefined方法 getApplicationContext() 未定义
【发布时间】:2013-05-21 20:18:28
【问题描述】:
public void onProviderDisabled(String provider) {
    Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT);


}

这就是我所拥有的,它显示一个错误并告诉我 MyLocationListener 类型的方法 getApplicationContext() 未定义

我应该怎么做才能避免这个错误

【问题讨论】:

  • 使用活动上下文而不是 getApplicationContext()
  • 这个方法在Activity里面吗?
  • 不,它不是实现 LocationListener 的类
  • 那你需要给它传递一个上下文
  • 看我的回答。希望对你有帮助

标签: android


【解决方案1】:

由于您不在Activity 中,您需要将Context 传递给班级。无论你在哪里实例化这个类,都会传递你的 Activities context

MyClass myClass = new MyClass(this);

然后在接受Context 作为param 的类中创建一个constructor 并使用它

public class MyClass {
    Context c;
    public MyClass(Context context) {
         c = context;
     }
}

那么当你需要使用它时

public void onProviderDisabled(String provider) {
    Toast.makeText(c, "Gps Disabled", Toast.LENGTH_SHORT);
}

【讨论】:

    【解决方案2】:

    这对我有用

    public class MyClass extends Activity

    【讨论】:

      【解决方案3】:

      如果你正在使用 ContentProvider 试试这个

      getContext()
      

      【讨论】:

        【解决方案4】:

        我通过扩展 Application 类来解决这个问题,我的类是 AppController:

        public class AppController extends Application{
            ...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-09
          • 1970-01-01
          • 2013-05-16
          • 1970-01-01
          • 2012-09-17
          • 2021-03-31
          • 2014-04-22
          • 2019-05-15
          相关资源
          最近更新 更多