Search code examples
androidandroid-pageradapter

Viewpager position 0 doesnt work with onPageSelected(0)


I cant set value for start page (position 0)

I mean QuestionPagerAdapter.tv.setText("default") must work in MainActivity's onPageSelected(int position) case 0: but it gives nullpoint. but it works for position > 0

PagerAdapter:

public class QuestionPagerAdapter extends PagerAdapter{

    public static TextView tv;

@Override
    public Object instantiateItem(View collection, int pos) {
        LayoutInflater inflater = (LayoutInflater) collection.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View page = inflater.inflate(R.layout.page_quiz, null);

         tv = (TextView)page.findViewById(R.id.questionText);


}
}

MainActivity:

    @Override
            protected void onCreate(final Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

               this.setContentView(R.layout.activity_main);

                mPager = (ViewPager)findViewById(R.id.pager);           
                    QuestionPagerAdapter mAdapter = new QuestionPagerAdapter();
                    mPager.setAdapter(mAdapter);

@Override
            public void onPageSelected(int position) {
                switch (position) {
            case 0: 
     //       QuestionPagerAdapter.tv.setText("default");  => doesnt works
                break;

                  default:
        QuestionPagerAdapter.tv.setText("default");  =>  works
                               break;

    }

Solution

  • Since you have the textView instance passed to AsyncTask, you can use onPreExecute() method to set the default value before it task starts executing. onPreExecute() method runs on UI thread so shouldn't be a issue.

    http://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute()