問題解決:Fragment not attached to Activity

一、問題引入

在Fragment中執行一段耗時任務,在任務未結束的時候,重建Activity就會致使getActivity()null,全部用到getActivity()的地方都會引發空指針異常,若是使用了getResources()方法,就會致使Fragment not attached to Activityjava

爲了重現這一異常,咱們編寫以下代碼:android

  • 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();
                break;
        }
    }
}
  • SecondFragment.java
public class SecondFragment extends Fragment {
    
    public SecondFragment() {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_second, container, false);
    }
}
  • fragment_first.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="cc.duduhuo.fragmentattachdemo.fragment.FirstFragment">

    <TextView
        android:id="@+id/tvMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="The First Fragment" />

    <Button
        android:id="@+id/btnStartTask"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="耗時任務" />

    <Button
        android:id="@+id/btnRecreate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="重建Activity" />
</LinearLayout>
  • fragment_second.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="cc.duduhuo.fragmentattachdemo.fragment.SecondFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="The Second Fragment" />

</FrameLayout>
  • MainActivity.java
public class MainActivity extends FragmentActivity {
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager = (ViewPager) this.findViewById(R.id.pager);
        initial();
    }

    private void initial() {
        List<Fragment> fragmentList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        fragmentList.add(new FirstFragment());
        fragmentList.add(new SecondFragment());
        titleList.add("First");
        titleList.add("Second");

        MyFragmentPageAdapter adapter = new MyFragmentPageAdapter(getSupportFragmentManager(), fragmentList, titleList);
        mViewPager.setAdapter(adapter);
    }

    private class MyFragmentPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> titleList;

        public MyFragmentPageAdapter(FragmentManager fm, List<Fragment> fragmentList, List<String> titleList) {
            super(fm);
            this.fragmentList = fragmentList;
            this.titleList = titleList;
        }

        @Override
        public Fragment getItem(int position) {
            return (fragmentList == null || fragmentList.size() == 0) ? null : fragmentList.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return (titleList.size() > position) ? titleList.get(position) : "";
        }

        @Override
        public int getCount() {
            return fragmentList == null ? 0 : fragmentList.size();
        }
    }
}
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="cc.duduhuo.fragmentattachdemo.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v4.view.PagerTabStrip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top" />
    </android.support.v4.view.ViewPager>
</LinearLayout>

當點擊FirstFragment裏面的「耗時任務」按鈕時,會執行一個2000ms的任務(上面的代碼是用休眠2000ms代替一個耗時任務)。若是點過以後靜靜等待2000ms,上面的TextView的文本就會變成FragmentAttachDemo,並不會報出任何異常。可是當咱們點擊「耗時任務」按鈕以後,在它還未執行完畢時,點擊下面的「重建ACTIVITY」按鈕,很快程序就會崩潰。app

控制檯打印出來的信息以下圖所示:
錯誤信息ide

除了點擊「重建ACTIVITY」按鈕以外,點擊「耗時任務」按鈕以後當即旋轉手機屏幕也會致使此異常,由於默認狀況下屏幕旋轉也會重建Activity。ui

二、問題解決

FirstFragmentonPostExecute()方法中的this

tvMsg.setText(getResources().getString(R.string.app_name));

改成.net

if (isAdded()) {
    tvMsg.setText(getResources().getString(R.string.app_name));
}

isAdded()方法能夠判斷當前的Fragment是否已經添加到Activity中,只有當Fragment已經添加到Activity中時才執行getResources()等方法。指針

另請參考:http://stackoverflow.com/questions/10919240/fragment-myfragment-not-attached-to-activitycode

固然,以上只是引發該異常的一個例子,並不能解決全部「Fragment not attached to Activity」的問題。xml

三、代碼下載

Demo代碼下載

相關文章
相關標籤/搜索