问题解决:Fragment not attached to Activity
1、问题引入
在Fragment中执行一段耗时任务,在任务未结束的时候,重建Activity就会导致getActivity()
为null
,所有用到getActivity()
的地方都会引起空指针异常,如果使用了getResources()
方法,就会导致Fragment not attached to Activity
。
为了重现这一异常,我们编写如下代码:
- FirstFragment.java
public class FirstFragment extends Fragment implements View.OnClickListener {
private TextView tvMsg;
private Button btnStartTask, btnRecreate;
private static final String TAG = "FirstFragment";
public FirstFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
tvMsg = (TextView) view.findViewById(R.id.tvMsg);
btnStartTask = (Button) view.findViewById(R.id.btnStartTask);
btnRecreate = (Button) view.findViewById(R.id.btnRecreate);
btnStartTask.setOnClickListener(this);
btnRecreate.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartTask:
// 模拟一个耗时任务
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.d(TAG, "getActivity = " + getActivity());
tvMsg.setText(getResources().getString(R.string.app_name));
}
}.execute();
break;
case R.id.btnRecreate:
// 重新创建MainActivity
getActivity().recreate()