我试图从静态类访问应用程序,但收到此错误
The method getActivity() is undefined for the type PniemActivity.MyFragmentAdapter
但是当我离开 getActivity() 时,我收到以下消息:
Cannot make a static reference to the non-static method getApplication() from the type Activity
这是我的代码。
private static class MyFragmentAdapter extends FragmentPagerAdapter{
private final int NUM_OF_PAGES = 10;
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public Fragment getItem(int index){
return PageFragment.newInstance("Hoi "+ index );
}
@Override
public int getCount(){
appData = ((myApp) getActivity().getApplication()).slaughterData;
return NUM_OF_PAGES;
}
}
我想从我的数据库中获取所需的 fragment 数量,这就是我想访问我的应用程序的原因。
有什么想法吗?
谢谢
最佳答案
据我所知, getActivity() 是 Fragment 上的方法,而不是 FragmentPageAdapter 上的方法。 You could get the current Fragment from the FragmentManager (你有引用),但我可能会按照弗拉基米尔在评论中建议的那样做:
- 将扩展 Application 的类添加到您的 AndroidManifest:
- 实现单例模式(使用 getInstance 方法)或简单地添加对您的应用程序子类的公共(public)静态引用
关于java - 从 astatic 类获取应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848299/