0

Using the latest Android Studio with a project with Fragments. All is well until rotating the screen with a fragment up. Get the error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xx/com.xxx.xxx.MainActivity}:

android.view.InflateException: Binary XML file line #7: Error inflating class fragment

The xml for the main activity looks like this

<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">

<fragment
    android:id="@+id/fragment"
    android:name="com.xxx.xxx.MainActivityFragment"
    tools:layout="@layout/fragment_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</FrameLayout>

Line 7 is the fragment definition as provided from Android Studio project create. I have done some searching on this and have not found the reason why the inflator is having a problem on rotation when recreating the fragment.

Otherwise without rotation all seems to be working fine.

ort11
  • 3,359
  • 4
  • 36
  • 69
  • 1
    Do you have a different layout for landscape orientation? Or perhaps the problem is in the `fragment_main` layout instead? – Karakuri Jul 21 '15 at 13:59

1 Answers1

0

You should have a constructor like this:

public class TestClass extends Fragment {
private View mView= null;
public TestClass() {

    setRetainInstance(true);
}

Also it is better to have onResume like below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_report_list, container, false);
    mListView = (AbsListView) mView.findViewById(android.R.id.list);

    Task reportTask = new Task(mView);
    reportTask.execute();

    return mView;

}

@Override
public void onResume(){
    super.onResume();

    Task reportTask = new Task(mView);
    reportTask.execute();
}

Don't forget to catch the exception. Just catch it and do nothing!

private void showProgressDialog() {
    if (mDialog == null) {
        mDialog = new ProgressDialog(getActivity());
        mDialog.setMessage("Loading. Please wait...");
        mDialog.setIndeterminate(false);
        mDialog.setCancelable(true);
    }
    mDialog.show();
}

private void dismissProgressDialog() {

    try{
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.cancel();
            mDialog.dismiss();
        }
    }catch (IllegalArgumentException ex){
        //do nothing
    }finally {
        mDialog = null;
    }
}

My test task is an async task. I hope it helps.

meda
  • 45,103
  • 14
  • 92
  • 122
Mohammad
  • 6,024
  • 3
  • 22
  • 30