Can't make static reference to non-static method ( Android getApplicationContext() )

The reason you were given for the error is correct. The fragments are static inner classes, they are in a scope in which an instance of the Activity does not exist. You then have a method which you call which can only be referenced from an instance of the Activity. Since you don't have an instance, you can't make that call. For this situation, there are two basic fixes. 

1) Remove the static keyword from the Fragment class definition. This would tie the definition of the class, and the instances of the class, to an instance of the the Activity and you would gain access to the Activity's instance methods. 

2) Call getActivity().getApplicationContext() instead. The method getActivity() comes from the Fragment class and gives you access to the methods of the Activity. If you need a specific method that you added to the Activity, then you would need to cast:((MyActivity)getActivity()).myMethod(); 

The second approach is probably the better one. The Fragment lifecycle is independent of the Activity lifecycle, and by making the Fragment an instance-level inner class you would end up tieing the two together. The FragmentManager may end up not liking it, and there could be issues when you do things like rotatge the screen.


https://coderanch.com/t/632507/Android/Mobile/Error-fix-static-reference-static


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 这是一个静态方法,用于返回Spring应用程序上下文对象。在Spring应用程序中,ApplicationContext是管理bean和处理依赖注入的中心接口。通常,在应用程序启动时,Spring会创建一个ApplicationContext对象,并将其保存在静态变量中以供其他组件使用。通过调用这个方法,可以在任何需要访问ApplicationContext的地方获取它。例如,在一个非Spring管理的类中,如果需要访问Spring管理的bean对象,就可以通过这个方法获取ApplicationContext,然后使用它来获取bean对象。 ### 回答2: 这段代码是一个静态方法,方法名为getApplicationContext,返回类型为ApplicationContext。 静态方法是指在类中可以直接调用,无需实例化对象。在这段代码中,我们可以通过类名直接调用这个方法,如:ClassName.getApplicationContext()。 这个方法的作用是获取ApplicationContext对象。ApplicationContext是Spring框架中的核心接口之一,用于管理和获取Bean对象。它提供了一些方法来获取Bean对象、注册Bean对象等操作。 在这段代码中,我们可以看到方法内部直接返回了一个变量applicationContext。这个变量应该是一个ApplicationContext对象。可以猜测,代码的其他部分可能会为这个变量赋值,或者通过注解@Configuration来自动获取ApplicationContext并赋值给这个变量。 通过调用getApplicationContext方法,我们可以在代码的其他地方获取到应用程序的ApplicationContext对象,并使用它来管理和获取其他的Bean对象。这样的设计可以更方便地操作和调用Bean对象,提高代码的模块性和可维护性。 总之,这段代码是一个静态方法,用于获取ApplicationContext对象,方便操作和调用Bean对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值