I am using ViewPager for a multiple-choice application that randomly selects thirty questions from a larger set. I do this in the PageAdapter that supplies the ViewPager pages.
The problem is that when the orientation changes, not only the pager but also the adapter is rebooted - I know how to save the current position of the pager, but when the adapter receives a reset, it also selects new questions from the set. What will be the right way to deal with this?
Also, the side question is, what would be the best way to register your choice with RadioGroups? Directly by click or in another way?
I am new to Android app development.
Activity:
public class MyActivity extends SherlockActivity { ActionBar actionBar; ViewPager pager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pager = new ViewPager(this); setContentView(pager); QuestionsAdapter adapter = new QuestionsAdapter(this); pager.setAdapter(adapter); int position = 0; if (savedInstanceState != null) { position = savedInstanceState.getInt("Q_NUMBER"); } pager.setCurrentItem(position); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { int position = pager.getCurrentItem(); savedInstanceState.putInt("Q_NUMBER", position); } }
Adapter:
class QuestionsAdapter extends PagerAdapter { Context context; QuestionsHelper dbQuestions; boolean exam; List<HashMap<String,Object>> examQuestions; public QuestionsAdapter(Context context, boolean exam) { this.context = context; this.examQuestions = GetQuestionsFromDB(30); } public Object instantiateItem(View collection, int position) { LayoutInflater inflater = (LayoutInflater) collection.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view; HashMap<String,Object> q; view = inflater.inflate(R.layout.exam_question_layout, null); q = getQuestion(position+1); ((TextView)view.findViewById(R.id.q_number)).setText(Integer.toString(position+1)+"."); ((TextView)view.findViewById(R.id.q_question)).setText(q.get("question").toString()); ((RadioButton)view.findViewById(R.id.q_answer_a)).setText(q.get("answer_a").toString()); ((RadioButton)view.findViewById(R.id.q_answer_b)).setText(q.get("answer_b").toString()); ((RadioButton)view.findViewById(R.id.q_answer_c)).setText(q.get("answer_c").toString()); ((ViewPager)collection).addView(view, 0); return view; } }
Czechnology
source share