Arun Arun - 1 year ago 64
Android Question

Fragments get loaded every time i switch tab, need efficient method

These are the screenshots of my application, ==> after loading the list from remote server the list is populated.

The problem for me is this,

When i move to the title Android - third tab(refer link) and switch back to java tab, the data is loading again.

How to make it load it single time and save it, so that it doesn't load every time?

The main activity is fragmentactivity which listens to tabadapter for changes in tabs.

This one is page adapter..

public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {

public Fragment getItem(int index) {

switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment2();

case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();

return null;

This one is fragmentActivity which uses page adapter

public void onCreate(Bundle savedInstanceState) {

// Initilization
viewPager = (ViewPager) findViewById(;
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());


// Adding Tabs
for (String tab_name : tabs) {
.setTabListener((TabListener) this));

* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

public void onPageSelected(int position) {
// on changing the page
// make respected tab selected

public void onPageScrolled(int arg0, float arg1, int arg2) {

public void onPageScrollStateChanged(int arg0) {
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub

public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
int position = mAdapter.getItemPosition(arg0);//;findItemPosition(arg0.getPosition());
viewPager=(getCurrentFocus()).ggetFragment(arg0, null);


Answer Source

According to revision 4 of the Support Package, a method was added to ViewPager which allows you to specify the number of offscreen pages to use, rather than the default which is 1. so you can load page rightside when move.

In your case, you want to specify 2, so that when you are on the third page, the first one is not destroyed, and vice-versa.

mViewPager = (ViewPager)findViewById(;

Thats it....

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download