android – show a blank screen when selecting a fragment for the second time-ThrowExceptions

Exception or error:

In my application, I have used the SherlockNavigationDrawer. By default, the navigationDrawer has 3 menu to opens 3 fragments. I have modified one of the following fragment. But when click for the second time on the menu of my fragment, screen not display anything! The first time, no problem; But the second time, a blank page is displayed.

In this case, if click on the default fragment menu in NavigationDrawer and then click on my fragment on the screen comes back on, but if click on my fragment menu again, screen show a blank page!

Also i have shown in my fragment a list of items, that by click on each item replace new fragment that show details of the specific item. but detail fragment is a display that is empty!!!

Friends! Where is the problem?

MainActivity Code:

public class ActivityMain extends SherlockFragmentActivity {

// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment_categorylist = new Fragment_CategoryList();
private CharSequence mDrawerTitle;
private CharSequence mTitle;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from drawer_main.xml
    setContentView(R.layout.drawer_main);

    // Get the Title
    mTitle = mDrawerTitle = getTitle();

    // Generate title
    title = new String[] { getString(R.string.TitleFragment1), 
            getString(R.string.TitleFragment2),
            getString(R.string.TitleFragment3) };

    // Generate subtitle
    subtitle = new String[] { getString(R.string.SubtitleFragment1),
            getString(R.string.SubtitleFragment2),
            getString(R.string.SubtitleFragment3) };

    // Generate icon
    icon = new int[] { R.drawable.action_about, R.drawable.action_settings,
            R.drawable.collections_cloud };

    // Locate DrawerLayout in drawer_main.xml
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Locate ListView in drawer_main.xml
    mDrawerList = (ListView) findViewById(R.id.listview_drawer);

    // Set a custom shadow that overlays the main content when the drawer
    // opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
            GravityCompat.START);

    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

    ActivitySwipeDetector swipe = new ActivitySwipeDetector(this);
    DrawerLayout swipe_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
    swipe_layout.setOnTouchListener(swipe);

    //LinearLayout swipe_layout2 = (LinearLayout) findViewById(R.id.fragment_pager_layout);
    //swipe_layout2.setOnTouchListener(swipe);

    // Pass string arrays to MenuListAdapter
    mMenuAdapter = new MenuListAdapter(ActivityMain.this, title, subtitle,
            icon);

    // Set the MenuListAdapter to the ListView
    mDrawerList.setAdapter(mMenuAdapter);

    // Capture listview menu item click
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // Enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        public void onDrawerClosed(View view) {
            // TODO Auto-generated method stub
            super.onDrawerClosed(view);
        }

        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub
            // Set the title on the action when drawer open
            getSupportActionBar().setTitle(mDrawerTitle);
            super.onDrawerOpened(drawerView);
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {

        if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            mDrawerLayout.openDrawer(mDrawerList);
        }
    }

    return super.onOptionsItemSelected(item);
}

// ListView click listener in the navigation drawer
private class DrawerItemClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Locate Position
    switch (position) {
    case 0:
        ft.replace(R.id.content_frame, fragment1);
        break;
    case 1:
        ft.replace(R.id.content_frame, fragment2);
        break;
    case 2:
        ft.replace(R.id.content_frame, fragment_categorylist);
        break;
    }
    ft.commit();
    mDrawerList.setItemChecked(position, true);

    // Get the title followed by the position
    setTitle(title[position]);
    // Close drawer
    mDrawerLayout.closeDrawer(mDrawerList);
}

Default Fragment Code:

public class Fragment3 extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment3, container, false);
    return rootView;
}

}

My Fragment (Modified Fragment) :

public class Fragment_CategoryList extends SherlockFragment {

static final int NUM_ITEMS = 1;

MyAdapter mAdapter;

ViewPager mPager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_pager, container,
            false);

    mAdapter = new MyAdapter(getSherlockActivity().getSupportFragmentManager());

    mPager = (ViewPager) rootView.findViewById(R.id.pager);

    mPager.setAdapter(mAdapter);

    // Watch for button clicks.
    Button button = (Button) rootView.findViewById(R.id.goto_first);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mPager.setCurrentItem(0);
        }
    });
    button = (Button) rootView.findViewById(R.id.goto_last);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mPager.setCurrentItem(NUM_ITEMS - 1);
        }
    });

    return rootView;
}


// ////////////////////////////////////////////////////////////////////////

public static class MyAdapter extends FragmentPagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    @Override
    public Fragment getItem(int position) {
        return ArrayListFragment.newInstance(position);
    }
}

public static class ArrayListFragment extends SherlockListFragment {
    int mNum;

    /**
     * Create a new instance of CountingFragment, providing "num" as an
     * argument.
     */
    static ArrayListFragment newInstance(int num) {
        ArrayListFragment f = new ArrayListFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its instance
     * number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container,
                false);
        View tv = v.findViewById(R.id.text);
        ((TextView) tv).setText("Fragment #" + mNum);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // setListAdapter(new ArrayAdapter<String>(getActivity(),
        // android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));

        DBAdapter db = new DBAdapter(getActivity());

        // Create an array to specify the fields we want to display in the
        // list (only TITLE)
        String[] from = new String[] { "title", "_id" };

        // and an array of the fields we want to bind those fields to (in
        // this case just text1)
        int[] to = new int[] { R.id.entry1, R.id.entry2 };

        ArrayList<HashMap<String, String>> categoryList = db.getAll();

        if (categoryList.size() != 0) {

            ListAdapter adapter = new SimpleAdapter(getActivity(),
                    categoryList,
                    R.layout.fragment_pager_list_entry, from, to);
            setListAdapter(adapter);
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {

        final FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();

        Fragment myFragment = new Fragment_QA();

        int idplus = (int)id + 1;
        Bundle args = new Bundle();
        args.putLong("cid", idplus);
        //myFragment.setArguments(args);

        ft.replace(((ViewGroup)(getView().getParent())).getId(), myFragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.addToBackStack(null);
        ft.commit();
    }
}

}

Main Activity UI:

<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<ListView
    android:id="@+id/listview_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#111"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp" />

My Fragment UI (Fragment_CategoryList):

<LinearLayout
    android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" 
    android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
        android:gravity="center" android:measureWithLargestChild="true"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0">
    <Button android:id="@+id/goto_first"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="FIRST">
    </Button>
    <Button android:id="@+id/goto_last"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="LAST">
    </Button>
</LinearLayout>

How to solve:

I don’t know if this question is still available but for someone could be a helpful answer.

That’s what you should do :

change from
android.support.v4.app.FragmentPagerAdapter to android.support.v4.app.FragmentStatePagerAdapter

Leave a Reply

Your email address will not be published. Required fields are marked *