Andrew Nguyen Andrew Nguyen - 12 days ago 6
Android Question

Using View Pager Adapter's Position to Change a Global Variable

I am attempting to change a global variable using the page position of a view pager.

Inside my view pager adapter:

public Object instantiateItem(ViewGroup container, int position) {

...

Global global = new Global();
switch(position){
case 0: global.setLocation("0");
break;
case 1: global.setLocation("1");
break;
case 2: global.setLocation("2");
break;
case 3: global.setLocation("3");
break;
default: global.setLocation("");
break;
}
return item_view;
}


If I switch pages, so does the location... However, when I toast the location, it is the incorrect location.

Example: I'm on page 3, global.getLocation = "2" or I'm on page 1, global.getLocation = "3"; (Answers appear to vary randomly)

What is incorrect about using the position of a view pager to change a global variable?

How can I accomplish this task correctly?

More code for attempted solution...

public class Location extends AppCompatActivity {
ViewPager viewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location2);

viewPager = (ViewPager)findViewById(R.id.myViewPager);
adapterLocation = new CustomSwipeAdapterLocation(this);
viewPager.setAdapter(adapterLocation);

int position = viewPager.getCurrentItem();
Toast.makeText(this, position,
Toast.LENGTH_LONG).show();
}
...


Error:

FATAL EXCEPTION: main
Process: andrewnguyen.finishedmoietyapp, PID: 5463
java.lang.RuntimeException: Unable to start activity ComponentInfo{andrewnguyen.finishedmoietyapp/andrewnguyen.finishedmoietyapp.Location}: android.content.res.Resources$NotFoundException: String resource ID #0x0


The error refers to line "int position = viewPager.getCurrentItem();"

Answer

You can use OnPageChangeListener and getting the position inside onPageSelected() method:

   viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Global global = new Global();
            switch(position){
                case 0: global.setLocation("0");
                    break;
                case 1: global.setLocation("1");
                    break;
                case 2: global.setLocation("2");
                    break;
                case 3: global.setLocation("3");
                    break;
                default: global.setLocation("");
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

Another option use getCurrentItem() to get the real item position:

viewPager.getCurrentItem();

if you use the position variable of instantiateItem() the position values are changing when new pages are instantiated