Android : How to switch to another activity after the last element in an array is displayed?

on Thursday, August 7, 2014


Im new in programming and im having difficulties with my program..I want to switch from main activity to result activity after the last element in array is displayed but seems like my if else statement is wrong..ive tried other references but its not working..Help please..



private int currentQuestion;
private String [] questions;
private String [] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;


int score=0;




@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}

public void init()
{
questions = new String[]{"What is my dog name?", "Who is my Crush?"};
answers = new String[]{"Butchick","Michael"};

currentQuestion = -1;


answerButton=(Button)findViewById(R.id.button1);
questionButton=(Button)findViewById(R.id.button2);

questionView=(TextView)findViewById(R.id.textView1);
answerView=(TextView)findViewById(R.id.textView2);
answerText=(EditText)findViewById(R.id.editText1);

answerButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
checkAnswer();
}});

questionButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {




if(currentQuestion<2){


currentQuestion++;

if(currentQuestion==questions.length)
currentQuestion=0;

questionView.setText(questions[currentQuestion]);
answerView.setText("");
answerText.setText("");

return;



}else{

Intent intent = new Intent(MainActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();


}




}});

}





public boolean isCorrect(String answer){
return(answer.equalsIgnoreCase(answers[currentQuestion]));


}


public void checkAnswer(){

String answer = answerText.getText().toString();

if(isCorrect(answer)){

answerView.setText("Youre Right!!");

score++;

}


else {
answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);

}



}


}


0 comments:

Post a Comment