当前位置:首页 » JAVA技术教程

android fragment getActivity() null

2014-03-06 20:10 本站整理 浏览(13590)

android fragment getActivity() null,有需要的朋友可以参考下。

在使用fragment时候遇到了一个问题,如果这个应用是被系统回收的,再回到这个应用时,fragment调用getActivity返回null,该fragement无法显示

public class MainActivity extends ActionBarActivity
implements ActionBar.OnNavigationListener{

private PlaceholderFragment subjectList;

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

subjectList = (PlaceholderFragment)PlaceholderFragment.instantiate(this,PlaceholderFragment.class.getName());
if (savedInstanceState == null) {

getSupportFragmentManager().beginTransaction()
.add(R.id.container, subjectList)

.commit();
}

}

}

public class PlaceholderFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor>{

public PlaceholderFragment() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);

return rootView;

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)

{
if (getActivity() == null) {

Log.v("PlaceholderFragment onActivityResult","Not Attached");
return;

}

}

}

错误代码如上,手动运行正常,退出再启动也是正常的。在系统回收资源再进入后出现问题Fragment 中getActivity() 为null。

刚开始以为是Activity和Fragment的lifecycle配合问题,可能某处的lifecycle处理不对,尝试在各个onXXX中增加处理,都不能解决问题。

后来想到有可能能是系统回收的时候仅回收了Activity,或者仅仅是将Activity和Fragment保存在某处,并未正真的释放。通过FragmentManager尝试找回先前的Fragment,问题解决。

在MainActivity中增加如下代码问题解决:

@Override
protected void onCreate(Bundle savedInstanceState) {

......

if (savedInstanceState == null)
subjectList = (PlaceholderFragment)PlaceholderFragment.instantiate(this,PlaceholderFragment.class.getName());

else
subjectList = (PlaceholderFragment)getSupportFragmentManager().getFragment(savedInstanceState,PlaceholderFragment.class.getName());

......

}

@Override

protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

getSupportFragmentManager().putFragment(outState,PlaceholderFragment.class.getName(),subjectList);
}